babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562
  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. /**
  159. * Observable that will be called when effect is bound.
  160. */
  161. this.onBindObservable = new BABYLON.Observable();
  162. /** @hidden */
  163. this._bonesComputationForcedToCPU = false;
  164. this._uniformBuffersNames = {};
  165. this._isReady = false;
  166. this._compilationError = "";
  167. this.name = baseName;
  168. if (attributesNamesOrOptions.attributes) {
  169. var options = attributesNamesOrOptions;
  170. this._engine = uniformsNamesOrEngine;
  171. this._attributesNames = options.attributes;
  172. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  173. this._samplers = options.samplers.slice();
  174. this.defines = options.defines;
  175. this.onError = options.onError;
  176. this.onCompiled = options.onCompiled;
  177. this._fallbacks = options.fallbacks;
  178. this._indexParameters = options.indexParameters;
  179. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  180. if (options.uniformBuffersNames) {
  181. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  182. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  183. }
  184. }
  185. }
  186. else {
  187. this._engine = engine;
  188. this.defines = defines;
  189. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  190. this._samplers = samplers ? samplers.slice() : [];
  191. this._attributesNames = attributesNamesOrOptions;
  192. this.onError = onError;
  193. this.onCompiled = onCompiled;
  194. this._indexParameters = indexParameters;
  195. this._fallbacks = fallbacks;
  196. }
  197. this.uniqueId = Effect._uniqueIdSeed++;
  198. var vertexSource;
  199. var fragmentSource;
  200. if (baseName.vertexElement) {
  201. vertexSource = document.getElementById(baseName.vertexElement);
  202. if (!vertexSource) {
  203. vertexSource = baseName.vertexElement;
  204. }
  205. }
  206. else {
  207. vertexSource = baseName.vertex || baseName;
  208. }
  209. if (baseName.fragmentElement) {
  210. fragmentSource = document.getElementById(baseName.fragmentElement);
  211. if (!fragmentSource) {
  212. fragmentSource = baseName.fragmentElement;
  213. }
  214. }
  215. else {
  216. fragmentSource = baseName.fragment || baseName;
  217. }
  218. this._loadVertexShader(vertexSource, function (vertexCode) {
  219. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  220. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  221. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  222. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  223. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  224. if (baseName) {
  225. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  226. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  227. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  228. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  229. }
  230. else {
  231. _this._vertexSourceCode = migratedVertexCode;
  232. _this._fragmentSourceCode = migratedFragmentCode;
  233. }
  234. _this._prepareEffect();
  235. });
  236. });
  237. });
  238. });
  239. });
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @hidden */
  348. Effect.prototype._loadVertexShader = function (vertex, callback) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. callback(vertexCode);
  354. return;
  355. }
  356. }
  357. // Base64 encoded ?
  358. if (vertex.substr(0, 7) === "base64:") {
  359. var vertexBinary = window.atob(vertex.substr(7));
  360. callback(vertexBinary);
  361. return;
  362. }
  363. // Is in local store ?
  364. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  365. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  366. return;
  367. }
  368. var vertexShaderUrl;
  369. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  370. vertexShaderUrl = vertex;
  371. }
  372. else {
  373. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  374. }
  375. // Vertex shader
  376. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  377. };
  378. /** @hidden */
  379. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  380. if (BABYLON.Tools.IsWindowObjectExist()) {
  381. // DOM element ?
  382. if (fragment instanceof HTMLElement) {
  383. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  384. callback(fragmentCode);
  385. return;
  386. }
  387. }
  388. // Base64 encoded ?
  389. if (fragment.substr(0, 7) === "base64:") {
  390. var fragmentBinary = window.atob(fragment.substr(7));
  391. callback(fragmentBinary);
  392. return;
  393. }
  394. // Is in local store ?
  395. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  396. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  397. return;
  398. }
  399. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  400. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  401. return;
  402. }
  403. var fragmentShaderUrl;
  404. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  405. fragmentShaderUrl = fragment;
  406. }
  407. else {
  408. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  409. }
  410. // Fragment shader
  411. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  412. };
  413. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  414. // Rebuild shaders source code
  415. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  416. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  417. vertexCode = prefix + vertexCode;
  418. fragmentCode = prefix + fragmentCode;
  419. // Number lines of shaders source code
  420. var i = 2;
  421. var regex = /\n/gm;
  422. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  423. i = 2;
  424. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  425. // Dump shaders name and formatted source code
  426. if (this.name.vertexElement) {
  427. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  428. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  429. }
  430. else if (this.name.vertex) {
  431. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  432. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  433. }
  434. else {
  435. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  436. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  437. }
  438. };
  439. ;
  440. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  441. var preparedSourceCode = this._processPrecision(sourceCode);
  442. if (this._engine.webGLVersion == 1) {
  443. callback(preparedSourceCode);
  444. return;
  445. }
  446. // Already converted
  447. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  448. callback(preparedSourceCode.replace("#version 300 es", ""));
  449. return;
  450. }
  451. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  452. // Remove extensions
  453. // #extension GL_OES_standard_derivatives : enable
  454. // #extension GL_EXT_shader_texture_lod : enable
  455. // #extension GL_EXT_frag_depth : enable
  456. // #extension GL_EXT_draw_buffers : require
  457. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  458. var result = preparedSourceCode.replace(regex, "");
  459. // Migrate to GLSL v300
  460. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  461. result = result.replace(/attribute[ \t]/g, "in ");
  462. result = result.replace(/[ \t]attribute/g, " in");
  463. if (isFragment) {
  464. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  465. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  466. result = result.replace(/texture2D\s*\(/g, "texture(");
  467. result = result.replace(/textureCube\s*\(/g, "texture(");
  468. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  469. result = result.replace(/gl_FragColor/g, "glFragColor");
  470. result = result.replace(/gl_FragData/g, "glFragData");
  471. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  472. }
  473. callback(result);
  474. };
  475. Effect.prototype._processIncludes = function (sourceCode, callback) {
  476. var _this = this;
  477. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  478. var match = regex.exec(sourceCode);
  479. var returnValue = new String(sourceCode);
  480. while (match != null) {
  481. var includeFile = match[1];
  482. // Uniform declaration
  483. if (includeFile.indexOf("__decl__") !== -1) {
  484. includeFile = includeFile.replace(/__decl__/, "");
  485. if (this._engine.supportsUniformBuffers) {
  486. includeFile = includeFile.replace(/Vertex/, "Ubo");
  487. includeFile = includeFile.replace(/Fragment/, "Ubo");
  488. }
  489. includeFile = includeFile + "Declaration";
  490. }
  491. if (Effect.IncludesShadersStore[includeFile]) {
  492. // Substitution
  493. var includeContent = Effect.IncludesShadersStore[includeFile];
  494. if (match[2]) {
  495. var splits = match[3].split(",");
  496. for (var index = 0; index < splits.length; index += 2) {
  497. var source = new RegExp(splits[index], "g");
  498. var dest = splits[index + 1];
  499. includeContent = includeContent.replace(source, dest);
  500. }
  501. }
  502. if (match[4]) {
  503. var indexString = match[5];
  504. if (indexString.indexOf("..") !== -1) {
  505. var indexSplits = indexString.split("..");
  506. var minIndex = parseInt(indexSplits[0]);
  507. var maxIndex = parseInt(indexSplits[1]);
  508. var sourceIncludeContent = includeContent.slice(0);
  509. includeContent = "";
  510. if (isNaN(maxIndex)) {
  511. maxIndex = this._indexParameters[indexSplits[1]];
  512. }
  513. for (var i = minIndex; i < maxIndex; i++) {
  514. if (!this._engine.supportsUniformBuffers) {
  515. // Ubo replacement
  516. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  517. return p1 + "{X}";
  518. });
  519. }
  520. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  521. }
  522. }
  523. else {
  524. if (!this._engine.supportsUniformBuffers) {
  525. // Ubo replacement
  526. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  527. return p1 + "{X}";
  528. });
  529. }
  530. includeContent = includeContent.replace(/\{X\}/g, indexString);
  531. }
  532. }
  533. // Replace
  534. returnValue = returnValue.replace(match[0], includeContent);
  535. }
  536. else {
  537. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  538. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  539. Effect.IncludesShadersStore[includeFile] = fileContent;
  540. _this._processIncludes(returnValue, callback);
  541. });
  542. return;
  543. }
  544. match = regex.exec(sourceCode);
  545. }
  546. callback(returnValue);
  547. };
  548. Effect.prototype._processPrecision = function (source) {
  549. if (source.indexOf("precision highp float") === -1) {
  550. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  551. source = "precision mediump float;\n" + source;
  552. }
  553. else {
  554. source = "precision highp float;\n" + source;
  555. }
  556. }
  557. else {
  558. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  559. source = source.replace("precision highp float", "precision mediump float");
  560. }
  561. }
  562. return source;
  563. };
  564. /**
  565. * Recompiles the webGL program
  566. * @param vertexSourceCode The source code for the vertex shader.
  567. * @param fragmentSourceCode The source code for the fragment shader.
  568. * @param onCompiled Callback called when completed.
  569. * @param onError Callback called on error.
  570. */
  571. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  572. var _this = this;
  573. this._isReady = false;
  574. this._vertexSourceCodeOverride = vertexSourceCode;
  575. this._fragmentSourceCodeOverride = fragmentSourceCode;
  576. this.onError = function (effect, error) {
  577. if (onError) {
  578. onError(error);
  579. }
  580. };
  581. this.onCompiled = function () {
  582. var scenes = _this.getEngine().scenes;
  583. for (var i = 0; i < scenes.length; i++) {
  584. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  585. }
  586. if (onCompiled) {
  587. onCompiled(_this._program);
  588. }
  589. };
  590. this._fallbacks = null;
  591. this._prepareEffect();
  592. };
  593. /**
  594. * Gets the uniform locations of the the specified variable names
  595. * @param names THe names of the variables to lookup.
  596. * @returns Array of locations in the same order as variable names.
  597. */
  598. Effect.prototype.getSpecificUniformLocations = function (names) {
  599. var engine = this._engine;
  600. return engine.getUniforms(this._program, names);
  601. };
  602. /**
  603. * Prepares the effect
  604. */
  605. Effect.prototype._prepareEffect = function () {
  606. var attributesNames = this._attributesNames;
  607. var defines = this.defines;
  608. var fallbacks = this._fallbacks;
  609. this._valueCache = {};
  610. var previousProgram = this._program;
  611. try {
  612. var engine = this._engine;
  613. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  614. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  615. }
  616. else {
  617. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  618. }
  619. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  620. if (engine.supportsUniformBuffers) {
  621. for (var name in this._uniformBuffersNames) {
  622. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  623. }
  624. }
  625. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  626. this._attributes = engine.getAttributes(this._program, attributesNames);
  627. var index;
  628. for (index = 0; index < this._samplers.length; index++) {
  629. var sampler = this.getUniform(this._samplers[index]);
  630. if (sampler == null) {
  631. this._samplers.splice(index, 1);
  632. index--;
  633. }
  634. }
  635. engine.bindSamplers(this);
  636. this._compilationError = "";
  637. this._isReady = true;
  638. if (this.onCompiled) {
  639. this.onCompiled(this);
  640. }
  641. this.onCompileObservable.notifyObservers(this);
  642. this.onCompileObservable.clear();
  643. // Unbind mesh reference in fallbacks
  644. if (this._fallbacks) {
  645. this._fallbacks.unBindMesh();
  646. }
  647. if (previousProgram) {
  648. this.getEngine()._deleteProgram(previousProgram);
  649. }
  650. }
  651. catch (e) {
  652. this._compilationError = e.message;
  653. // Let's go through fallbacks then
  654. BABYLON.Tools.Error("Unable to compile effect:");
  655. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  656. return " " + uniform;
  657. }));
  658. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  659. return " " + attribute;
  660. }));
  661. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  662. BABYLON.Tools.Error("Error: " + this._compilationError);
  663. if (previousProgram) {
  664. this._program = previousProgram;
  665. this._isReady = true;
  666. if (this.onError) {
  667. this.onError(this, this._compilationError);
  668. }
  669. this.onErrorObservable.notifyObservers(this);
  670. }
  671. if (fallbacks && fallbacks.isMoreFallbacks) {
  672. BABYLON.Tools.Error("Trying next fallback.");
  673. this.defines = fallbacks.reduce(this.defines, this);
  674. this._prepareEffect();
  675. }
  676. else { // Sorry we did everything we can
  677. if (this.onError) {
  678. this.onError(this, this._compilationError);
  679. }
  680. this.onErrorObservable.notifyObservers(this);
  681. this.onErrorObservable.clear();
  682. // Unbind mesh reference in fallbacks
  683. if (this._fallbacks) {
  684. this._fallbacks.unBindMesh();
  685. }
  686. }
  687. }
  688. };
  689. Object.defineProperty(Effect.prototype, "isSupported", {
  690. /**
  691. * Checks if the effect is supported. (Must be called after compilation)
  692. */
  693. get: function () {
  694. return this._compilationError === "";
  695. },
  696. enumerable: true,
  697. configurable: true
  698. });
  699. /**
  700. * Binds a texture to the engine to be used as output of the shader.
  701. * @param channel Name of the output variable.
  702. * @param texture Texture to bind.
  703. */
  704. Effect.prototype._bindTexture = function (channel, texture) {
  705. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  706. };
  707. /**
  708. * Sets a texture on the engine to be used in the shader.
  709. * @param channel Name of the sampler variable.
  710. * @param texture Texture to set.
  711. */
  712. Effect.prototype.setTexture = function (channel, texture) {
  713. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  714. };
  715. /**
  716. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  717. * @param channel Name of the sampler variable.
  718. * @param texture Texture to set.
  719. */
  720. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  721. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  722. };
  723. /**
  724. * Sets an array of textures on the engine to be used in the shader.
  725. * @param channel Name of the variable.
  726. * @param textures Textures to set.
  727. */
  728. Effect.prototype.setTextureArray = function (channel, textures) {
  729. if (this._samplers.indexOf(channel + "Ex") === -1) {
  730. var initialPos = this._samplers.indexOf(channel);
  731. for (var index = 1; index < textures.length; index++) {
  732. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  733. }
  734. }
  735. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  736. };
  737. /**
  738. * 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)
  739. * @param channel Name of the sampler variable.
  740. * @param postProcess Post process to get the input texture from.
  741. */
  742. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  743. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  744. };
  745. /**
  746. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  747. * 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)
  748. * @param channel Name of the sampler variable.
  749. * @param postProcess Post process to get the output texture from.
  750. */
  751. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  752. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  753. };
  754. /** @hidden */
  755. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  756. var cache = this._valueCache[uniformName];
  757. var flag = matrix.updateFlag;
  758. if (cache !== undefined && cache === flag) {
  759. return false;
  760. }
  761. this._valueCache[uniformName] = flag;
  762. return true;
  763. };
  764. /** @hidden */
  765. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  766. var cache = this._valueCache[uniformName];
  767. if (!cache) {
  768. cache = [x, y];
  769. this._valueCache[uniformName] = cache;
  770. return true;
  771. }
  772. var changed = false;
  773. if (cache[0] !== x) {
  774. cache[0] = x;
  775. changed = true;
  776. }
  777. if (cache[1] !== y) {
  778. cache[1] = y;
  779. changed = true;
  780. }
  781. return changed;
  782. };
  783. /** @hidden */
  784. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  785. var cache = this._valueCache[uniformName];
  786. if (!cache) {
  787. cache = [x, y, z];
  788. this._valueCache[uniformName] = cache;
  789. return true;
  790. }
  791. var changed = false;
  792. if (cache[0] !== x) {
  793. cache[0] = x;
  794. changed = true;
  795. }
  796. if (cache[1] !== y) {
  797. cache[1] = y;
  798. changed = true;
  799. }
  800. if (cache[2] !== z) {
  801. cache[2] = z;
  802. changed = true;
  803. }
  804. return changed;
  805. };
  806. /** @hidden */
  807. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  808. var cache = this._valueCache[uniformName];
  809. if (!cache) {
  810. cache = [x, y, z, w];
  811. this._valueCache[uniformName] = cache;
  812. return true;
  813. }
  814. var changed = false;
  815. if (cache[0] !== x) {
  816. cache[0] = x;
  817. changed = true;
  818. }
  819. if (cache[1] !== y) {
  820. cache[1] = y;
  821. changed = true;
  822. }
  823. if (cache[2] !== z) {
  824. cache[2] = z;
  825. changed = true;
  826. }
  827. if (cache[3] !== w) {
  828. cache[3] = w;
  829. changed = true;
  830. }
  831. return changed;
  832. };
  833. /**
  834. * Binds a buffer to a uniform.
  835. * @param buffer Buffer to bind.
  836. * @param name Name of the uniform variable to bind to.
  837. */
  838. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  839. var bufferName = this._uniformBuffersNames[name];
  840. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  841. return;
  842. }
  843. Effect._baseCache[bufferName] = buffer;
  844. this._engine.bindUniformBufferBase(buffer, bufferName);
  845. };
  846. /**
  847. * Binds block to a uniform.
  848. * @param blockName Name of the block to bind.
  849. * @param index Index to bind.
  850. */
  851. Effect.prototype.bindUniformBlock = function (blockName, index) {
  852. this._engine.bindUniformBlock(this._program, blockName, index);
  853. };
  854. /**
  855. * Sets an interger value on a uniform variable.
  856. * @param uniformName Name of the variable.
  857. * @param value Value to be set.
  858. * @returns this effect.
  859. */
  860. Effect.prototype.setInt = function (uniformName, value) {
  861. var cache = this._valueCache[uniformName];
  862. if (cache !== undefined && cache === value)
  863. return this;
  864. this._valueCache[uniformName] = value;
  865. this._engine.setInt(this.getUniform(uniformName), value);
  866. return this;
  867. };
  868. /**
  869. * Sets an int array on a uniform variable.
  870. * @param uniformName Name of the variable.
  871. * @param array array to be set.
  872. * @returns this effect.
  873. */
  874. Effect.prototype.setIntArray = function (uniformName, array) {
  875. this._valueCache[uniformName] = null;
  876. this._engine.setIntArray(this.getUniform(uniformName), array);
  877. return this;
  878. };
  879. /**
  880. * 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)
  881. * @param uniformName Name of the variable.
  882. * @param array array to be set.
  883. * @returns this effect.
  884. */
  885. Effect.prototype.setIntArray2 = function (uniformName, array) {
  886. this._valueCache[uniformName] = null;
  887. this._engine.setIntArray2(this.getUniform(uniformName), array);
  888. return this;
  889. };
  890. /**
  891. * 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)
  892. * @param uniformName Name of the variable.
  893. * @param array array to be set.
  894. * @returns this effect.
  895. */
  896. Effect.prototype.setIntArray3 = function (uniformName, array) {
  897. this._valueCache[uniformName] = null;
  898. this._engine.setIntArray3(this.getUniform(uniformName), array);
  899. return this;
  900. };
  901. /**
  902. * 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)
  903. * @param uniformName Name of the variable.
  904. * @param array array to be set.
  905. * @returns this effect.
  906. */
  907. Effect.prototype.setIntArray4 = function (uniformName, array) {
  908. this._valueCache[uniformName] = null;
  909. this._engine.setIntArray4(this.getUniform(uniformName), array);
  910. return this;
  911. };
  912. /**
  913. * Sets an float array on a uniform variable.
  914. * @param uniformName Name of the variable.
  915. * @param array array to be set.
  916. * @returns this effect.
  917. */
  918. Effect.prototype.setFloatArray = function (uniformName, array) {
  919. this._valueCache[uniformName] = null;
  920. this._engine.setFloatArray(this.getUniform(uniformName), array);
  921. return this;
  922. };
  923. /**
  924. * 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)
  925. * @param uniformName Name of the variable.
  926. * @param array array to be set.
  927. * @returns this effect.
  928. */
  929. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  930. this._valueCache[uniformName] = null;
  931. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  932. return this;
  933. };
  934. /**
  935. * 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)
  936. * @param uniformName Name of the variable.
  937. * @param array array to be set.
  938. * @returns this effect.
  939. */
  940. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  941. this._valueCache[uniformName] = null;
  942. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  943. return this;
  944. };
  945. /**
  946. * 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)
  947. * @param uniformName Name of the variable.
  948. * @param array array to be set.
  949. * @returns this effect.
  950. */
  951. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  952. this._valueCache[uniformName] = null;
  953. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  954. return this;
  955. };
  956. /**
  957. * Sets an array on a uniform variable.
  958. * @param uniformName Name of the variable.
  959. * @param array array to be set.
  960. * @returns this effect.
  961. */
  962. Effect.prototype.setArray = function (uniformName, array) {
  963. this._valueCache[uniformName] = null;
  964. this._engine.setArray(this.getUniform(uniformName), array);
  965. return this;
  966. };
  967. /**
  968. * 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)
  969. * @param uniformName Name of the variable.
  970. * @param array array to be set.
  971. * @returns this effect.
  972. */
  973. Effect.prototype.setArray2 = function (uniformName, array) {
  974. this._valueCache[uniformName] = null;
  975. this._engine.setArray2(this.getUniform(uniformName), array);
  976. return this;
  977. };
  978. /**
  979. * 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)
  980. * @param uniformName Name of the variable.
  981. * @param array array to be set.
  982. * @returns this effect.
  983. */
  984. Effect.prototype.setArray3 = function (uniformName, array) {
  985. this._valueCache[uniformName] = null;
  986. this._engine.setArray3(this.getUniform(uniformName), array);
  987. return this;
  988. };
  989. /**
  990. * 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)
  991. * @param uniformName Name of the variable.
  992. * @param array array to be set.
  993. * @returns this effect.
  994. */
  995. Effect.prototype.setArray4 = function (uniformName, array) {
  996. this._valueCache[uniformName] = null;
  997. this._engine.setArray4(this.getUniform(uniformName), array);
  998. return this;
  999. };
  1000. /**
  1001. * Sets matrices on a uniform variable.
  1002. * @param uniformName Name of the variable.
  1003. * @param matrices matrices to be set.
  1004. * @returns this effect.
  1005. */
  1006. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1007. if (!matrices) {
  1008. return this;
  1009. }
  1010. this._valueCache[uniformName] = null;
  1011. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1012. return this;
  1013. };
  1014. /**
  1015. * Sets matrix on a uniform variable.
  1016. * @param uniformName Name of the variable.
  1017. * @param matrix matrix to be set.
  1018. * @returns this effect.
  1019. */
  1020. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1021. if (this._cacheMatrix(uniformName, matrix)) {
  1022. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1023. }
  1024. return this;
  1025. };
  1026. /**
  1027. * 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)
  1028. * @param uniformName Name of the variable.
  1029. * @param matrix matrix to be set.
  1030. * @returns this effect.
  1031. */
  1032. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1033. this._valueCache[uniformName] = null;
  1034. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1035. return this;
  1036. };
  1037. /**
  1038. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1039. * @param uniformName Name of the variable.
  1040. * @param matrix matrix to be set.
  1041. * @returns this effect.
  1042. */
  1043. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1044. this._valueCache[uniformName] = null;
  1045. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1046. return this;
  1047. };
  1048. /**
  1049. * Sets a float on a uniform variable.
  1050. * @param uniformName Name of the variable.
  1051. * @param value value to be set.
  1052. * @returns this effect.
  1053. */
  1054. Effect.prototype.setFloat = function (uniformName, value) {
  1055. var cache = this._valueCache[uniformName];
  1056. if (cache !== undefined && cache === value)
  1057. return this;
  1058. this._valueCache[uniformName] = value;
  1059. this._engine.setFloat(this.getUniform(uniformName), value);
  1060. return this;
  1061. };
  1062. /**
  1063. * Sets a boolean on a uniform variable.
  1064. * @param uniformName Name of the variable.
  1065. * @param bool value to be set.
  1066. * @returns this effect.
  1067. */
  1068. Effect.prototype.setBool = function (uniformName, bool) {
  1069. var cache = this._valueCache[uniformName];
  1070. if (cache !== undefined && cache === bool)
  1071. return this;
  1072. this._valueCache[uniformName] = bool;
  1073. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets a Vector2 on a uniform variable.
  1078. * @param uniformName Name of the variable.
  1079. * @param vector2 vector2 to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1083. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1084. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1085. }
  1086. return this;
  1087. };
  1088. /**
  1089. * Sets a float2 on a uniform variable.
  1090. * @param uniformName Name of the variable.
  1091. * @param x First float in float2.
  1092. * @param y Second float in float2.
  1093. * @returns this effect.
  1094. */
  1095. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1096. if (this._cacheFloat2(uniformName, x, y)) {
  1097. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1098. }
  1099. return this;
  1100. };
  1101. /**
  1102. * Sets a Vector3 on a uniform variable.
  1103. * @param uniformName Name of the variable.
  1104. * @param vector3 Value to be set.
  1105. * @returns this effect.
  1106. */
  1107. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1108. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1109. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1110. }
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float3 on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param x First float in float3.
  1117. * @param y Second float in float3.
  1118. * @param z Third float in float3.
  1119. * @returns this effect.
  1120. */
  1121. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1122. if (this._cacheFloat3(uniformName, x, y, z)) {
  1123. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1124. }
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a Vector4 on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param vector4 Value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1134. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1135. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1136. }
  1137. return this;
  1138. };
  1139. /**
  1140. * Sets a float4 on a uniform variable.
  1141. * @param uniformName Name of the variable.
  1142. * @param x First float in float4.
  1143. * @param y Second float in float4.
  1144. * @param z Third float in float4.
  1145. * @param w Fourth float in float4.
  1146. * @returns this effect.
  1147. */
  1148. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1149. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1150. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1151. }
  1152. return this;
  1153. };
  1154. /**
  1155. * Sets a Color3 on a uniform variable.
  1156. * @param uniformName Name of the variable.
  1157. * @param color3 Value to be set.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setColor3 = function (uniformName, color3) {
  1161. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1162. this._engine.setColor3(this.getUniform(uniformName), color3);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Color4 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param color3 Value to be set.
  1170. * @param alpha Alpha value to be set.
  1171. * @returns this effect.
  1172. */
  1173. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1174. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1175. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1176. }
  1177. return this;
  1178. };
  1179. /**
  1180. * Sets a Color4 on a uniform variable
  1181. * @param uniformName defines the name of the variable
  1182. * @param color4 defines the value to be set
  1183. * @returns this effect.
  1184. */
  1185. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1186. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1187. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1188. }
  1189. return this;
  1190. };
  1191. /**
  1192. * Resets the cache of effects.
  1193. */
  1194. Effect.ResetCache = function () {
  1195. Effect._baseCache = {};
  1196. };
  1197. Effect._uniqueIdSeed = 0;
  1198. Effect._baseCache = {};
  1199. /**
  1200. * Store of each shader (The can be looked up using effect.key)
  1201. */
  1202. Effect.ShadersStore = {};
  1203. /**
  1204. * Store of each included file for a shader (The can be looked up using effect.key)
  1205. */
  1206. Effect.IncludesShadersStore = {};
  1207. return Effect;
  1208. }());
  1209. BABYLON.Effect = Effect;
  1210. })(BABYLON || (BABYLON = {}));
  1211. //# sourceMappingURL=babylon.effect.js.map
  1212. //# sourceMappingURL=babylon.types.js.map
  1213. var BABYLON;
  1214. (function (BABYLON) {
  1215. var KeyboardEventTypes = /** @class */ (function () {
  1216. function KeyboardEventTypes() {
  1217. }
  1218. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1219. get: function () {
  1220. return KeyboardEventTypes._KEYDOWN;
  1221. },
  1222. enumerable: true,
  1223. configurable: true
  1224. });
  1225. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1226. get: function () {
  1227. return KeyboardEventTypes._KEYUP;
  1228. },
  1229. enumerable: true,
  1230. configurable: true
  1231. });
  1232. KeyboardEventTypes._KEYDOWN = 0x01;
  1233. KeyboardEventTypes._KEYUP = 0x02;
  1234. return KeyboardEventTypes;
  1235. }());
  1236. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1237. var KeyboardInfo = /** @class */ (function () {
  1238. function KeyboardInfo(type, event) {
  1239. this.type = type;
  1240. this.event = event;
  1241. }
  1242. return KeyboardInfo;
  1243. }());
  1244. BABYLON.KeyboardInfo = KeyboardInfo;
  1245. /**
  1246. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1247. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1248. */
  1249. var KeyboardInfoPre = /** @class */ (function (_super) {
  1250. __extends(KeyboardInfoPre, _super);
  1251. function KeyboardInfoPre(type, event) {
  1252. var _this = _super.call(this, type, event) || this;
  1253. _this.skipOnPointerObservable = false;
  1254. return _this;
  1255. }
  1256. return KeyboardInfoPre;
  1257. }(KeyboardInfo));
  1258. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1259. })(BABYLON || (BABYLON = {}));
  1260. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1261. var BABYLON;
  1262. (function (BABYLON) {
  1263. var PointerEventTypes = /** @class */ (function () {
  1264. function PointerEventTypes() {
  1265. }
  1266. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1267. get: function () {
  1268. return PointerEventTypes._POINTERDOWN;
  1269. },
  1270. enumerable: true,
  1271. configurable: true
  1272. });
  1273. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1274. get: function () {
  1275. return PointerEventTypes._POINTERUP;
  1276. },
  1277. enumerable: true,
  1278. configurable: true
  1279. });
  1280. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1281. get: function () {
  1282. return PointerEventTypes._POINTERMOVE;
  1283. },
  1284. enumerable: true,
  1285. configurable: true
  1286. });
  1287. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1288. get: function () {
  1289. return PointerEventTypes._POINTERWHEEL;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1295. get: function () {
  1296. return PointerEventTypes._POINTERPICK;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1302. get: function () {
  1303. return PointerEventTypes._POINTERTAP;
  1304. },
  1305. enumerable: true,
  1306. configurable: true
  1307. });
  1308. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1309. get: function () {
  1310. return PointerEventTypes._POINTERDOUBLETAP;
  1311. },
  1312. enumerable: true,
  1313. configurable: true
  1314. });
  1315. PointerEventTypes._POINTERDOWN = 0x01;
  1316. PointerEventTypes._POINTERUP = 0x02;
  1317. PointerEventTypes._POINTERMOVE = 0x04;
  1318. PointerEventTypes._POINTERWHEEL = 0x08;
  1319. PointerEventTypes._POINTERPICK = 0x10;
  1320. PointerEventTypes._POINTERTAP = 0x20;
  1321. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1322. return PointerEventTypes;
  1323. }());
  1324. BABYLON.PointerEventTypes = PointerEventTypes;
  1325. var PointerInfoBase = /** @class */ (function () {
  1326. function PointerInfoBase(type, event) {
  1327. this.type = type;
  1328. this.event = event;
  1329. }
  1330. return PointerInfoBase;
  1331. }());
  1332. BABYLON.PointerInfoBase = PointerInfoBase;
  1333. /**
  1334. * This class is used to store pointer related info for the onPrePointerObservable event.
  1335. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1336. */
  1337. var PointerInfoPre = /** @class */ (function (_super) {
  1338. __extends(PointerInfoPre, _super);
  1339. function PointerInfoPre(type, event, localX, localY) {
  1340. var _this = _super.call(this, type, event) || this;
  1341. /**
  1342. * Ray from a pointer if availible (eg. 6dof controller)
  1343. */
  1344. _this.ray = null;
  1345. _this.skipOnPointerObservable = false;
  1346. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1347. return _this;
  1348. }
  1349. return PointerInfoPre;
  1350. }(PointerInfoBase));
  1351. BABYLON.PointerInfoPre = PointerInfoPre;
  1352. /**
  1353. * This type contains all the data related to a pointer event in Babylon.js.
  1354. * 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.
  1355. */
  1356. var PointerInfo = /** @class */ (function (_super) {
  1357. __extends(PointerInfo, _super);
  1358. function PointerInfo(type, event, pickInfo) {
  1359. var _this = _super.call(this, type, event) || this;
  1360. _this.pickInfo = pickInfo;
  1361. return _this;
  1362. }
  1363. return PointerInfo;
  1364. }(PointerInfoBase));
  1365. BABYLON.PointerInfo = PointerInfo;
  1366. })(BABYLON || (BABYLON = {}));
  1367. //# sourceMappingURL=babylon.pointerEvents.js.map
  1368. var BABYLON;
  1369. (function (BABYLON) {
  1370. BABYLON.ToGammaSpace = 1 / 2.2;
  1371. BABYLON.ToLinearSpace = 2.2;
  1372. BABYLON.Epsilon = 0.001;
  1373. /**
  1374. * Class used to hold a RBG color
  1375. */
  1376. var Color3 = /** @class */ (function () {
  1377. /**
  1378. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1379. * @param r defines the red component (between 0 and 1, default is 0)
  1380. * @param g defines the green component (between 0 and 1, default is 0)
  1381. * @param b defines the blue component (between 0 and 1, default is 0)
  1382. */
  1383. function Color3(
  1384. /**
  1385. * Defines the red component (between 0 and 1, default is 0)
  1386. */
  1387. r,
  1388. /**
  1389. * Defines the green component (between 0 and 1, default is 0)
  1390. */
  1391. g,
  1392. /**
  1393. * Defines the blue component (between 0 and 1, default is 0)
  1394. */
  1395. b) {
  1396. if (r === void 0) { r = 0; }
  1397. if (g === void 0) { g = 0; }
  1398. if (b === void 0) { b = 0; }
  1399. this.r = r;
  1400. this.g = g;
  1401. this.b = b;
  1402. }
  1403. /**
  1404. * Creates a string with the Color3 current values
  1405. * @returns the string representation of the Color3 object
  1406. */
  1407. Color3.prototype.toString = function () {
  1408. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1409. };
  1410. /**
  1411. * Returns the string "Color3"
  1412. * @returns "Color3"
  1413. */
  1414. Color3.prototype.getClassName = function () {
  1415. return "Color3";
  1416. };
  1417. /**
  1418. * Compute the Color3 hash code
  1419. * @returns an unique number that can be used to hash Color3 objects
  1420. */
  1421. Color3.prototype.getHashCode = function () {
  1422. var hash = this.r || 0;
  1423. hash = (hash * 397) ^ (this.g || 0);
  1424. hash = (hash * 397) ^ (this.b || 0);
  1425. return hash;
  1426. };
  1427. // Operators
  1428. /**
  1429. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1430. * @param array defines the array where to store the r,g,b components
  1431. * @param index defines an optional index in the target array to define where to start storing values
  1432. * @returns the current Color3 object
  1433. */
  1434. Color3.prototype.toArray = function (array, index) {
  1435. if (index === undefined) {
  1436. index = 0;
  1437. }
  1438. array[index] = this.r;
  1439. array[index + 1] = this.g;
  1440. array[index + 2] = this.b;
  1441. return this;
  1442. };
  1443. /**
  1444. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1445. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1446. * @returns a new {BABYLON.Color4} object
  1447. */
  1448. Color3.prototype.toColor4 = function (alpha) {
  1449. if (alpha === void 0) { alpha = 1; }
  1450. return new Color4(this.r, this.g, this.b, alpha);
  1451. };
  1452. /**
  1453. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1454. * @returns the new array
  1455. */
  1456. Color3.prototype.asArray = function () {
  1457. var result = new Array();
  1458. this.toArray(result, 0);
  1459. return result;
  1460. };
  1461. /**
  1462. * Returns the luminance value
  1463. * @returns a float value
  1464. */
  1465. Color3.prototype.toLuminance = function () {
  1466. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1467. };
  1468. /**
  1469. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1470. * @param otherColor defines the second operand
  1471. * @returns the new Color3 object
  1472. */
  1473. Color3.prototype.multiply = function (otherColor) {
  1474. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1475. };
  1476. /**
  1477. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1478. * @param otherColor defines the second operand
  1479. * @param result defines the Color3 object where to store the result
  1480. * @returns the current Color3
  1481. */
  1482. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1483. result.r = this.r * otherColor.r;
  1484. result.g = this.g * otherColor.g;
  1485. result.b = this.b * otherColor.b;
  1486. return this;
  1487. };
  1488. /**
  1489. * Determines equality between Color3 objects
  1490. * @param otherColor defines the second operand
  1491. * @returns true if the rgb values are equal to the given ones
  1492. */
  1493. Color3.prototype.equals = function (otherColor) {
  1494. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1495. };
  1496. /**
  1497. * Determines equality between the current Color3 object and a set of r,b,g values
  1498. * @param r defines the red component to check
  1499. * @param g defines the green component to check
  1500. * @param b defines the blue component to check
  1501. * @returns true if the rgb values are equal to the given ones
  1502. */
  1503. Color3.prototype.equalsFloats = function (r, g, b) {
  1504. return this.r === r && this.g === g && this.b === b;
  1505. };
  1506. /**
  1507. * Multiplies in place each rgb value by scale
  1508. * @param scale defines the scaling factor
  1509. * @returns the updated Color3
  1510. */
  1511. Color3.prototype.scale = function (scale) {
  1512. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1513. };
  1514. /**
  1515. * Multiplies the rgb values by scale and stores the result into "result"
  1516. * @param scale defines the scaling factor
  1517. * @param result defines the Color3 object where to store the result
  1518. * @returns the unmodified current Color3
  1519. */
  1520. Color3.prototype.scaleToRef = function (scale, result) {
  1521. result.r = this.r * scale;
  1522. result.g = this.g * scale;
  1523. result.b = this.b * scale;
  1524. return this;
  1525. };
  1526. /**
  1527. * Scale the current Color3 values by a factor and add the result to a given Color3
  1528. * @param scale defines the scale factor
  1529. * @param result defines color to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1533. result.r += this.r * scale;
  1534. result.g += this.g * scale;
  1535. result.b += this.b * scale;
  1536. return this;
  1537. };
  1538. /**
  1539. * Clamps the rgb values by the min and max values and stores the result into "result"
  1540. * @param min defines minimum clamping value (default is 0)
  1541. * @param max defines maximum clamping value (default is 1)
  1542. * @param result defines color to store the result into
  1543. * @returns the original Color3
  1544. */
  1545. Color3.prototype.clampToRef = function (min, max, result) {
  1546. if (min === void 0) { min = 0; }
  1547. if (max === void 0) { max = 1; }
  1548. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1549. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1550. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1551. return this;
  1552. };
  1553. /**
  1554. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1555. * @param otherColor defines the second operand
  1556. * @returns the new Color3
  1557. */
  1558. Color3.prototype.add = function (otherColor) {
  1559. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1560. };
  1561. /**
  1562. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1563. * @param otherColor defines the second operand
  1564. * @param result defines Color3 object to store the result into
  1565. * @returns the unmodified current Color3
  1566. */
  1567. Color3.prototype.addToRef = function (otherColor, result) {
  1568. result.r = this.r + otherColor.r;
  1569. result.g = this.g + otherColor.g;
  1570. result.b = this.b + otherColor.b;
  1571. return this;
  1572. };
  1573. /**
  1574. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1575. * @param otherColor defines the second operand
  1576. * @returns the new Color3
  1577. */
  1578. Color3.prototype.subtract = function (otherColor) {
  1579. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1580. };
  1581. /**
  1582. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1583. * @param otherColor defines the second operand
  1584. * @param result defines Color3 object to store the result into
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.subtractToRef = function (otherColor, result) {
  1588. result.r = this.r - otherColor.r;
  1589. result.g = this.g - otherColor.g;
  1590. result.b = this.b - otherColor.b;
  1591. return this;
  1592. };
  1593. /**
  1594. * Copy the current object
  1595. * @returns a new Color3 copied the current one
  1596. */
  1597. Color3.prototype.clone = function () {
  1598. return new Color3(this.r, this.g, this.b);
  1599. };
  1600. /**
  1601. * Copies the rgb values from the source in the current Color3
  1602. * @param source defines the source Color3 object
  1603. * @returns the updated Color3 object
  1604. */
  1605. Color3.prototype.copyFrom = function (source) {
  1606. this.r = source.r;
  1607. this.g = source.g;
  1608. this.b = source.b;
  1609. return this;
  1610. };
  1611. /**
  1612. * Updates the Color3 rgb values from the given floats
  1613. * @param r defines the red component to read from
  1614. * @param g defines the green component to read from
  1615. * @param b defines the blue component to read from
  1616. * @returns the current Color3 object
  1617. */
  1618. Color3.prototype.copyFromFloats = function (r, g, b) {
  1619. this.r = r;
  1620. this.g = g;
  1621. this.b = b;
  1622. return this;
  1623. };
  1624. /**
  1625. * Updates the Color3 rgb values from the given floats
  1626. * @param r defines the red component to read from
  1627. * @param g defines the green component to read from
  1628. * @param b defines the blue component to read from
  1629. * @returns the current Color3 object
  1630. */
  1631. Color3.prototype.set = function (r, g, b) {
  1632. return this.copyFromFloats(r, g, b);
  1633. };
  1634. /**
  1635. * Compute the Color3 hexadecimal code as a string
  1636. * @returns a string containing the hexadecimal representation of the Color3 object
  1637. */
  1638. Color3.prototype.toHexString = function () {
  1639. var intR = (this.r * 255) | 0;
  1640. var intG = (this.g * 255) | 0;
  1641. var intB = (this.b * 255) | 0;
  1642. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1643. };
  1644. /**
  1645. * Computes a new Color3 converted from the current one to linear space
  1646. * @returns a new Color3 object
  1647. */
  1648. Color3.prototype.toLinearSpace = function () {
  1649. var convertedColor = new Color3();
  1650. this.toLinearSpaceToRef(convertedColor);
  1651. return convertedColor;
  1652. };
  1653. /**
  1654. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1655. * @param convertedColor defines the Color3 object where to store the linear space version
  1656. * @returns the unmodified Color3
  1657. */
  1658. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1659. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1660. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1661. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1662. return this;
  1663. };
  1664. /**
  1665. * Computes a new Color3 converted from the current one to gamma space
  1666. * @returns a new Color3 object
  1667. */
  1668. Color3.prototype.toGammaSpace = function () {
  1669. var convertedColor = new Color3();
  1670. this.toGammaSpaceToRef(convertedColor);
  1671. return convertedColor;
  1672. };
  1673. /**
  1674. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1675. * @param convertedColor defines the Color3 object where to store the gamma space version
  1676. * @returns the unmodified Color3
  1677. */
  1678. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1679. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1680. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1681. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1682. return this;
  1683. };
  1684. // Statics
  1685. /**
  1686. * Creates a new Color3 from the string containing valid hexadecimal values
  1687. * @param hex defines a string containing valid hexadecimal values
  1688. * @returns a new Color3 object
  1689. */
  1690. Color3.FromHexString = function (hex) {
  1691. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1692. return new Color3(0, 0, 0);
  1693. }
  1694. var r = parseInt(hex.substring(1, 3), 16);
  1695. var g = parseInt(hex.substring(3, 5), 16);
  1696. var b = parseInt(hex.substring(5, 7), 16);
  1697. return Color3.FromInts(r, g, b);
  1698. };
  1699. /**
  1700. * Creates a new Vector3 from the starting index of the given array
  1701. * @param array defines the source array
  1702. * @param offset defines an offset in the source array
  1703. * @returns a new Color3 object
  1704. */
  1705. Color3.FromArray = function (array, offset) {
  1706. if (offset === void 0) { offset = 0; }
  1707. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1708. };
  1709. /**
  1710. * Creates a new Color3 from integer values (< 256)
  1711. * @param r defines the red component to read from (value between 0 and 255)
  1712. * @param g defines the green component to read from (value between 0 and 255)
  1713. * @param b defines the blue component to read from (value between 0 and 255)
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.FromInts = function (r, g, b) {
  1717. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1718. };
  1719. /**
  1720. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1721. * @param start defines the start Color3 value
  1722. * @param end defines the end Color3 value
  1723. * @param amount defines the gradient value between start and end
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Lerp = function (start, end, amount) {
  1727. var r = start.r + ((end.r - start.r) * amount);
  1728. var g = start.g + ((end.g - start.g) * amount);
  1729. var b = start.b + ((end.b - start.b) * amount);
  1730. return new Color3(r, g, b);
  1731. };
  1732. /**
  1733. * Returns a Color3 value containing a red color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Red = function () { return new Color3(1, 0, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a green color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Green = function () { return new Color3(0, 1, 0); };
  1742. /**
  1743. * Returns a Color3 value containing a blue color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1747. /**
  1748. * Returns a Color3 value containing a black color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Black = function () { return new Color3(0, 0, 0); };
  1752. /**
  1753. * Returns a Color3 value containing a white color
  1754. * @returns a new Color3 object
  1755. */
  1756. Color3.White = function () { return new Color3(1, 1, 1); };
  1757. /**
  1758. * Returns a Color3 value containing a purple color
  1759. * @returns a new Color3 object
  1760. */
  1761. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1762. /**
  1763. * Returns a Color3 value containing a magenta color
  1764. * @returns a new Color3 object
  1765. */
  1766. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1767. /**
  1768. * Returns a Color3 value containing a yellow color
  1769. * @returns a new Color3 object
  1770. */
  1771. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1772. /**
  1773. * Returns a Color3 value containing a gray color
  1774. * @returns a new Color3 object
  1775. */
  1776. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1777. /**
  1778. * Returns a Color3 value containing a teal color
  1779. * @returns a new Color3 object
  1780. */
  1781. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1782. /**
  1783. * Returns a Color3 value containing a random color
  1784. * @returns a new Color3 object
  1785. */
  1786. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1787. return Color3;
  1788. }());
  1789. BABYLON.Color3 = Color3;
  1790. /**
  1791. * Class used to hold a RBGA color
  1792. */
  1793. var Color4 = /** @class */ (function () {
  1794. /**
  1795. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1796. * @param r defines the red component (between 0 and 1, default is 0)
  1797. * @param g defines the green component (between 0 and 1, default is 0)
  1798. * @param b defines the blue component (between 0 and 1, default is 0)
  1799. * @param a defines the alpha component (between 0 and 1, default is 1)
  1800. */
  1801. function Color4(
  1802. /**
  1803. * Defines the red component (between 0 and 1, default is 0)
  1804. */
  1805. r,
  1806. /**
  1807. * Defines the green component (between 0 and 1, default is 0)
  1808. */
  1809. g,
  1810. /**
  1811. * Defines the blue component (between 0 and 1, default is 0)
  1812. */
  1813. b,
  1814. /**
  1815. * Defines the alpha component (between 0 and 1, default is 1)
  1816. */
  1817. a) {
  1818. if (r === void 0) { r = 0; }
  1819. if (g === void 0) { g = 0; }
  1820. if (b === void 0) { b = 0; }
  1821. if (a === void 0) { a = 1; }
  1822. this.r = r;
  1823. this.g = g;
  1824. this.b = b;
  1825. this.a = a;
  1826. }
  1827. // Operators
  1828. /**
  1829. * Adds in place the given Color4 values to the current Color4 object
  1830. * @param right defines the second operand
  1831. * @returns the current updated Color4 object
  1832. */
  1833. Color4.prototype.addInPlace = function (right) {
  1834. this.r += right.r;
  1835. this.g += right.g;
  1836. this.b += right.b;
  1837. this.a += right.a;
  1838. return this;
  1839. };
  1840. /**
  1841. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1842. * @returns the new array
  1843. */
  1844. Color4.prototype.asArray = function () {
  1845. var result = new Array();
  1846. this.toArray(result, 0);
  1847. return result;
  1848. };
  1849. /**
  1850. * Stores from the starting index in the given array the Color4 successive values
  1851. * @param array defines the array where to store the r,g,b components
  1852. * @param index defines an optional index in the target array to define where to start storing values
  1853. * @returns the current Color4 object
  1854. */
  1855. Color4.prototype.toArray = function (array, index) {
  1856. if (index === undefined) {
  1857. index = 0;
  1858. }
  1859. array[index] = this.r;
  1860. array[index + 1] = this.g;
  1861. array[index + 2] = this.b;
  1862. array[index + 3] = this.a;
  1863. return this;
  1864. };
  1865. /**
  1866. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1867. * @param right defines the second operand
  1868. * @returns a new Color4 object
  1869. */
  1870. Color4.prototype.add = function (right) {
  1871. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1872. };
  1873. /**
  1874. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1875. * @param right defines the second operand
  1876. * @returns a new Color4 object
  1877. */
  1878. Color4.prototype.subtract = function (right) {
  1879. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1880. };
  1881. /**
  1882. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1883. * @param right defines the second operand
  1884. * @param result defines the Color4 object where to store the result
  1885. * @returns the current Color4 object
  1886. */
  1887. Color4.prototype.subtractToRef = function (right, result) {
  1888. result.r = this.r - right.r;
  1889. result.g = this.g - right.g;
  1890. result.b = this.b - right.b;
  1891. result.a = this.a - right.a;
  1892. return this;
  1893. };
  1894. /**
  1895. * Creates a new Color4 with the current Color4 values multiplied by scale
  1896. * @param scale defines the scaling factor to apply
  1897. * @returns a new Color4 object
  1898. */
  1899. Color4.prototype.scale = function (scale) {
  1900. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1901. };
  1902. /**
  1903. * Multiplies the current Color4 values by scale and stores the result in "result"
  1904. * @param scale defines the scaling factor to apply
  1905. * @param result defines the Color4 object where to store the result
  1906. * @returns the current unmodified Color4
  1907. */
  1908. Color4.prototype.scaleToRef = function (scale, result) {
  1909. result.r = this.r * scale;
  1910. result.g = this.g * scale;
  1911. result.b = this.b * scale;
  1912. result.a = this.a * scale;
  1913. return this;
  1914. };
  1915. /**
  1916. * Scale the current Color4 values by a factor and add the result to a given Color4
  1917. * @param scale defines the scale factor
  1918. * @param result defines the Color4 object where to store the result
  1919. * @returns the unmodified current Color4
  1920. */
  1921. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1922. result.r += this.r * scale;
  1923. result.g += this.g * scale;
  1924. result.b += this.b * scale;
  1925. result.a += this.a * scale;
  1926. return this;
  1927. };
  1928. /**
  1929. * Clamps the rgb values by the min and max values and stores the result into "result"
  1930. * @param min defines minimum clamping value (default is 0)
  1931. * @param max defines maximum clamping value (default is 1)
  1932. * @param result defines color to store the result into.
  1933. * @returns the cuurent Color4
  1934. */
  1935. Color4.prototype.clampToRef = function (min, max, result) {
  1936. if (min === void 0) { min = 0; }
  1937. if (max === void 0) { max = 1; }
  1938. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1939. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1940. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1941. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1942. return this;
  1943. };
  1944. /**
  1945. * Multipy an Color4 value by another and return a new Color4 object
  1946. * @param color defines the Color4 value to multiply by
  1947. * @returns a new Color4 object
  1948. */
  1949. Color4.prototype.multiply = function (color) {
  1950. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1951. };
  1952. /**
  1953. * Multipy a Color4 value by another and push the result in a reference value
  1954. * @param color defines the Color4 value to multiply by
  1955. * @param result defines the Color4 to fill the result in
  1956. * @returns the result Color4
  1957. */
  1958. Color4.prototype.multiplyToRef = function (color, result) {
  1959. result.r = this.r * color.r;
  1960. result.g = this.g * color.g;
  1961. result.b = this.b * color.b;
  1962. result.a = this.a * color.a;
  1963. return result;
  1964. };
  1965. /**
  1966. * Creates a string with the Color4 current values
  1967. * @returns the string representation of the Color4 object
  1968. */
  1969. Color4.prototype.toString = function () {
  1970. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1971. };
  1972. /**
  1973. * Returns the string "Color4"
  1974. * @returns "Color4"
  1975. */
  1976. Color4.prototype.getClassName = function () {
  1977. return "Color4";
  1978. };
  1979. /**
  1980. * Compute the Color4 hash code
  1981. * @returns an unique number that can be used to hash Color4 objects
  1982. */
  1983. Color4.prototype.getHashCode = function () {
  1984. var hash = this.r || 0;
  1985. hash = (hash * 397) ^ (this.g || 0);
  1986. hash = (hash * 397) ^ (this.b || 0);
  1987. hash = (hash * 397) ^ (this.a || 0);
  1988. return hash;
  1989. };
  1990. /**
  1991. * Creates a new Color4 copied from the current one
  1992. * @returns a new Color4 object
  1993. */
  1994. Color4.prototype.clone = function () {
  1995. return new Color4(this.r, this.g, this.b, this.a);
  1996. };
  1997. /**
  1998. * Copies the given Color4 values into the current one
  1999. * @param source defines the source Color4 object
  2000. * @returns the current updated Color4 object
  2001. */
  2002. Color4.prototype.copyFrom = function (source) {
  2003. this.r = source.r;
  2004. this.g = source.g;
  2005. this.b = source.b;
  2006. this.a = source.a;
  2007. return this;
  2008. };
  2009. /**
  2010. * Copies the given float values into the current one
  2011. * @param r defines the red component to read from
  2012. * @param g defines the green component to read from
  2013. * @param b defines the blue component to read from
  2014. * @param a defines the alpha component to read from
  2015. * @returns the current updated Color4 object
  2016. */
  2017. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2018. this.r = r;
  2019. this.g = g;
  2020. this.b = b;
  2021. this.a = a;
  2022. return this;
  2023. };
  2024. /**
  2025. * Copies the given float values into the current one
  2026. * @param r defines the red component to read from
  2027. * @param g defines the green component to read from
  2028. * @param b defines the blue component to read from
  2029. * @param a defines the alpha component to read from
  2030. * @returns the current updated Color4 object
  2031. */
  2032. Color4.prototype.set = function (r, g, b, a) {
  2033. return this.copyFromFloats(r, g, b, a);
  2034. };
  2035. /**
  2036. * Compute the Color4 hexadecimal code as a string
  2037. * @returns a string containing the hexadecimal representation of the Color4 object
  2038. */
  2039. Color4.prototype.toHexString = function () {
  2040. var intR = (this.r * 255) | 0;
  2041. var intG = (this.g * 255) | 0;
  2042. var intB = (this.b * 255) | 0;
  2043. var intA = (this.a * 255) | 0;
  2044. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2045. };
  2046. /**
  2047. * Computes a new Color4 converted from the current one to linear space
  2048. * @returns a new Color4 object
  2049. */
  2050. Color4.prototype.toLinearSpace = function () {
  2051. var convertedColor = new Color4();
  2052. this.toLinearSpaceToRef(convertedColor);
  2053. return convertedColor;
  2054. };
  2055. /**
  2056. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2057. * @param convertedColor defines the Color4 object where to store the linear space version
  2058. * @returns the unmodified Color4
  2059. */
  2060. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2061. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2062. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2063. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2064. convertedColor.a = this.a;
  2065. return this;
  2066. };
  2067. /**
  2068. * Computes a new Color4 converted from the current one to gamma space
  2069. * @returns a new Color4 object
  2070. */
  2071. Color4.prototype.toGammaSpace = function () {
  2072. var convertedColor = new Color4();
  2073. this.toGammaSpaceToRef(convertedColor);
  2074. return convertedColor;
  2075. };
  2076. /**
  2077. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2078. * @param convertedColor defines the Color4 object where to store the gamma space version
  2079. * @returns the unmodified Color4
  2080. */
  2081. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2082. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2083. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2084. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2085. convertedColor.a = this.a;
  2086. return this;
  2087. };
  2088. // Statics
  2089. /**
  2090. * Creates a new Color4 from the string containing valid hexadecimal values
  2091. * @param hex defines a string containing valid hexadecimal values
  2092. * @returns a new Color4 object
  2093. */
  2094. Color4.FromHexString = function (hex) {
  2095. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2096. return new Color4(0.0, 0.0, 0.0, 0.0);
  2097. }
  2098. var r = parseInt(hex.substring(1, 3), 16);
  2099. var g = parseInt(hex.substring(3, 5), 16);
  2100. var b = parseInt(hex.substring(5, 7), 16);
  2101. var a = parseInt(hex.substring(7, 9), 16);
  2102. return Color4.FromInts(r, g, b, a);
  2103. };
  2104. /**
  2105. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2106. * @param left defines the start value
  2107. * @param right defines the end value
  2108. * @param amount defines the gradient factor
  2109. * @returns a new Color4 object
  2110. */
  2111. Color4.Lerp = function (left, right, amount) {
  2112. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2113. Color4.LerpToRef(left, right, amount, result);
  2114. return result;
  2115. };
  2116. /**
  2117. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2118. * @param left defines the start value
  2119. * @param right defines the end value
  2120. * @param amount defines the gradient factor
  2121. * @param result defines the Color4 object where to store data
  2122. */
  2123. Color4.LerpToRef = function (left, right, amount, result) {
  2124. result.r = left.r + (right.r - left.r) * amount;
  2125. result.g = left.g + (right.g - left.g) * amount;
  2126. result.b = left.b + (right.b - left.b) * amount;
  2127. result.a = left.a + (right.a - left.a) * amount;
  2128. };
  2129. /**
  2130. * Creates a new Color4 from the starting index element of the given array
  2131. * @param array defines the source array to read from
  2132. * @param offset defines the offset in the source array
  2133. * @returns a new Color4 object
  2134. */
  2135. Color4.FromArray = function (array, offset) {
  2136. if (offset === void 0) { offset = 0; }
  2137. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2138. };
  2139. /**
  2140. * Creates a new Color3 from integer values (< 256)
  2141. * @param r defines the red component to read from (value between 0 and 255)
  2142. * @param g defines the green component to read from (value between 0 and 255)
  2143. * @param b defines the blue component to read from (value between 0 and 255)
  2144. * @param a defines the alpha component to read from (value between 0 and 255)
  2145. * @returns a new Color3 object
  2146. */
  2147. Color4.FromInts = function (r, g, b, a) {
  2148. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2149. };
  2150. /**
  2151. * Check the content of a given array and convert it to an array containing RGBA data
  2152. * If the original array was already containing count * 4 values then it is returned directly
  2153. * @param colors defines the array to check
  2154. * @param count defines the number of RGBA data to expect
  2155. * @returns an array containing count * 4 values (RGBA)
  2156. */
  2157. Color4.CheckColors4 = function (colors, count) {
  2158. // Check if color3 was used
  2159. if (colors.length === count * 3) {
  2160. var colors4 = [];
  2161. for (var index = 0; index < colors.length; index += 3) {
  2162. var newIndex = (index / 3) * 4;
  2163. colors4[newIndex] = colors[index];
  2164. colors4[newIndex + 1] = colors[index + 1];
  2165. colors4[newIndex + 2] = colors[index + 2];
  2166. colors4[newIndex + 3] = 1.0;
  2167. }
  2168. return colors4;
  2169. }
  2170. return colors;
  2171. };
  2172. return Color4;
  2173. }());
  2174. BABYLON.Color4 = Color4;
  2175. /**
  2176. * Class representing a vector containing 2 coordinates
  2177. */
  2178. var Vector2 = /** @class */ (function () {
  2179. /**
  2180. * Creates a new Vector2 from the given x and y coordinates
  2181. * @param x defines the first coordinate
  2182. * @param y defines the second coordinate
  2183. */
  2184. function Vector2(
  2185. /** defines the first coordinate */
  2186. x,
  2187. /** defines the second coordinate */
  2188. y) {
  2189. if (x === void 0) { x = 0; }
  2190. if (y === void 0) { y = 0; }
  2191. this.x = x;
  2192. this.y = y;
  2193. }
  2194. /**
  2195. * Gets a string with the Vector2 coordinates
  2196. * @returns a string with the Vector2 coordinates
  2197. */
  2198. Vector2.prototype.toString = function () {
  2199. return "{X: " + this.x + " Y:" + this.y + "}";
  2200. };
  2201. /**
  2202. * Gets class name
  2203. * @returns the string "Vector2"
  2204. */
  2205. Vector2.prototype.getClassName = function () {
  2206. return "Vector2";
  2207. };
  2208. /**
  2209. * Gets current vector hash code
  2210. * @returns the Vector2 hash code as a number
  2211. */
  2212. Vector2.prototype.getHashCode = function () {
  2213. var hash = this.x || 0;
  2214. hash = (hash * 397) ^ (this.y || 0);
  2215. return hash;
  2216. };
  2217. // Operators
  2218. /**
  2219. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2220. * @param array defines the source array
  2221. * @param index defines the offset in source array
  2222. * @returns the current Vector2
  2223. */
  2224. Vector2.prototype.toArray = function (array, index) {
  2225. if (index === void 0) { index = 0; }
  2226. array[index] = this.x;
  2227. array[index + 1] = this.y;
  2228. return this;
  2229. };
  2230. /**
  2231. * Copy the current vector to an array
  2232. * @returns a new array with 2 elements: the Vector2 coordinates.
  2233. */
  2234. Vector2.prototype.asArray = function () {
  2235. var result = new Array();
  2236. this.toArray(result, 0);
  2237. return result;
  2238. };
  2239. /**
  2240. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2241. * @param source defines the source Vector2
  2242. * @returns the current updated Vector2
  2243. */
  2244. Vector2.prototype.copyFrom = function (source) {
  2245. this.x = source.x;
  2246. this.y = source.y;
  2247. return this;
  2248. };
  2249. /**
  2250. * Sets the Vector2 coordinates with the given floats
  2251. * @param x defines the first coordinate
  2252. * @param y defines the second coordinate
  2253. * @returns the current updated Vector2
  2254. */
  2255. Vector2.prototype.copyFromFloats = function (x, y) {
  2256. this.x = x;
  2257. this.y = y;
  2258. return this;
  2259. };
  2260. /**
  2261. * Sets the Vector2 coordinates with the given floats
  2262. * @param x defines the first coordinate
  2263. * @param y defines the second coordinate
  2264. * @returns the current updated Vector2
  2265. */
  2266. Vector2.prototype.set = function (x, y) {
  2267. return this.copyFromFloats(x, y);
  2268. };
  2269. /**
  2270. * Add another vector with the current one
  2271. * @param otherVector defines the other vector
  2272. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2273. */
  2274. Vector2.prototype.add = function (otherVector) {
  2275. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2276. };
  2277. /**
  2278. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2279. * @param otherVector defines the other vector
  2280. * @param result defines the target vector
  2281. * @returns the unmodified current Vector2
  2282. */
  2283. Vector2.prototype.addToRef = function (otherVector, result) {
  2284. result.x = this.x + otherVector.x;
  2285. result.y = this.y + otherVector.y;
  2286. return this;
  2287. };
  2288. /**
  2289. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2290. * @param otherVector defines the other vector
  2291. * @returns the current updated Vector2
  2292. */
  2293. Vector2.prototype.addInPlace = function (otherVector) {
  2294. this.x += otherVector.x;
  2295. this.y += otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2300. * @param otherVector defines the other vector
  2301. * @returns a new Vector2
  2302. */
  2303. Vector2.prototype.addVector3 = function (otherVector) {
  2304. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2305. };
  2306. /**
  2307. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2308. * @param otherVector defines the other vector
  2309. * @returns a new Vector2
  2310. */
  2311. Vector2.prototype.subtract = function (otherVector) {
  2312. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2313. };
  2314. /**
  2315. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2316. * @param otherVector defines the other vector
  2317. * @param result defines the target vector
  2318. * @returns the unmodified current Vector2
  2319. */
  2320. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2321. result.x = this.x - otherVector.x;
  2322. result.y = this.y - otherVector.y;
  2323. return this;
  2324. };
  2325. /**
  2326. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2327. * @param otherVector defines the other vector
  2328. * @returns the current updated Vector2
  2329. */
  2330. Vector2.prototype.subtractInPlace = function (otherVector) {
  2331. this.x -= otherVector.x;
  2332. this.y -= otherVector.y;
  2333. return this;
  2334. };
  2335. /**
  2336. * Multiplies in place the current Vector2 coordinates by the given ones
  2337. * @param otherVector defines the other vector
  2338. * @returns the current updated Vector2
  2339. */
  2340. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2341. this.x *= otherVector.x;
  2342. this.y *= otherVector.y;
  2343. return this;
  2344. };
  2345. /**
  2346. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2347. * @param otherVector defines the other vector
  2348. * @returns a new Vector2
  2349. */
  2350. Vector2.prototype.multiply = function (otherVector) {
  2351. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2352. };
  2353. /**
  2354. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2355. * @param otherVector defines the other vector
  2356. * @param result defines the target vector
  2357. * @returns the unmodified current Vector2
  2358. */
  2359. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2360. result.x = this.x * otherVector.x;
  2361. result.y = this.y * otherVector.y;
  2362. return this;
  2363. };
  2364. /**
  2365. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2366. * @param x defines the first coordinate
  2367. * @param y defines the second coordinate
  2368. * @returns a new Vector2
  2369. */
  2370. Vector2.prototype.multiplyByFloats = function (x, y) {
  2371. return new Vector2(this.x * x, this.y * y);
  2372. };
  2373. /**
  2374. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2375. * @param otherVector defines the other vector
  2376. * @returns a new Vector2
  2377. */
  2378. Vector2.prototype.divide = function (otherVector) {
  2379. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2380. };
  2381. /**
  2382. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2383. * @param otherVector defines the other vector
  2384. * @param result defines the target vector
  2385. * @returns the unmodified current Vector2
  2386. */
  2387. Vector2.prototype.divideToRef = function (otherVector, result) {
  2388. result.x = this.x / otherVector.x;
  2389. result.y = this.y / otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Divides the current Vector3 coordinates by the given ones
  2394. * @param otherVector defines the other vector
  2395. * @returns the current updated Vector2
  2396. */
  2397. Vector2.prototype.divideInPlace = function (otherVector) {
  2398. return this.divideToRef(otherVector, this);
  2399. };
  2400. /**
  2401. * Gets a new Vector2 with current Vector2 negated coordinates
  2402. * @returns a new Vector2
  2403. */
  2404. Vector2.prototype.negate = function () {
  2405. return new Vector2(-this.x, -this.y);
  2406. };
  2407. /**
  2408. * Multiply the Vector2 coordinates by scale
  2409. * @param scale defines the scaling factor
  2410. * @returns the current updated Vector2
  2411. */
  2412. Vector2.prototype.scaleInPlace = function (scale) {
  2413. this.x *= scale;
  2414. this.y *= scale;
  2415. return this;
  2416. };
  2417. /**
  2418. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2419. * @param scale defines the scaling factor
  2420. * @returns a new Vector2
  2421. */
  2422. Vector2.prototype.scale = function (scale) {
  2423. var result = new Vector2(0, 0);
  2424. this.scaleToRef(scale, result);
  2425. return result;
  2426. };
  2427. /**
  2428. * Scale the current Vector2 values by a factor to a given Vector2
  2429. * @param scale defines the scale factor
  2430. * @param result defines the Vector2 object where to store the result
  2431. * @returns the unmodified current Vector2
  2432. */
  2433. Vector2.prototype.scaleToRef = function (scale, result) {
  2434. result.x = this.x * scale;
  2435. result.y = this.y * scale;
  2436. return this;
  2437. };
  2438. /**
  2439. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2440. * @param scale defines the scale factor
  2441. * @param result defines the Vector2 object where to store the result
  2442. * @returns the unmodified current Vector2
  2443. */
  2444. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2445. result.x += this.x * scale;
  2446. result.y += this.y * scale;
  2447. return this;
  2448. };
  2449. /**
  2450. * Gets a boolean if two vectors are equals
  2451. * @param otherVector defines the other vector
  2452. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2453. */
  2454. Vector2.prototype.equals = function (otherVector) {
  2455. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2456. };
  2457. /**
  2458. * Gets a boolean if two vectors are equals (using an epsilon value)
  2459. * @param otherVector defines the other vector
  2460. * @param epsilon defines the minimal distance to consider equality
  2461. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2462. */
  2463. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2464. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2465. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2466. };
  2467. // Properties
  2468. /**
  2469. * Gets the length of the vector
  2470. * @returns the vector length (float)
  2471. */
  2472. Vector2.prototype.length = function () {
  2473. return Math.sqrt(this.x * this.x + this.y * this.y);
  2474. };
  2475. /**
  2476. * Gets the vector squared length
  2477. * @returns the vector squared length (float)
  2478. */
  2479. Vector2.prototype.lengthSquared = function () {
  2480. return (this.x * this.x + this.y * this.y);
  2481. };
  2482. // Methods
  2483. /**
  2484. * Normalize the vector
  2485. * @returns the current updated Vector2
  2486. */
  2487. Vector2.prototype.normalize = function () {
  2488. var len = this.length();
  2489. if (len === 0)
  2490. return this;
  2491. var num = 1.0 / len;
  2492. this.x *= num;
  2493. this.y *= num;
  2494. return this;
  2495. };
  2496. /**
  2497. * Gets a new Vector2 copied from the Vector2
  2498. * @returns a new Vector2
  2499. */
  2500. Vector2.prototype.clone = function () {
  2501. return new Vector2(this.x, this.y);
  2502. };
  2503. // Statics
  2504. /**
  2505. * Gets a new Vector2(0, 0)
  2506. * @returns a new Vector2
  2507. */
  2508. Vector2.Zero = function () {
  2509. return new Vector2(0, 0);
  2510. };
  2511. /**
  2512. * Gets a new Vector2(1, 1)
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.One = function () {
  2516. return new Vector2(1, 1);
  2517. };
  2518. /**
  2519. * Gets a new Vector2 set from the given index element of the given array
  2520. * @param array defines the data source
  2521. * @param offset defines the offset in the data source
  2522. * @returns a new Vector2
  2523. */
  2524. Vector2.FromArray = function (array, offset) {
  2525. if (offset === void 0) { offset = 0; }
  2526. return new Vector2(array[offset], array[offset + 1]);
  2527. };
  2528. /**
  2529. * Sets "result" from the given index element of the given array
  2530. * @param array defines the data source
  2531. * @param offset defines the offset in the data source
  2532. * @param result defines the target vector
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2540. * @param value1 defines 1st point of control
  2541. * @param value2 defines 2nd point of control
  2542. * @param value3 defines 3rd point of control
  2543. * @param value4 defines 4th point of control
  2544. * @param amount defines the interpolation factor
  2545. * @returns a new Vector2
  2546. */
  2547. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2548. var squared = amount * amount;
  2549. var cubed = amount * squared;
  2550. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2551. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2552. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2553. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2554. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2555. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2556. return new Vector2(x, y);
  2557. };
  2558. /**
  2559. * 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".
  2560. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2561. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2562. * @param value defines the value to clamp
  2563. * @param min defines the lower limit
  2564. * @param max defines the upper limit
  2565. * @returns a new Vector2
  2566. */
  2567. Vector2.Clamp = function (value, min, max) {
  2568. var x = value.x;
  2569. x = (x > max.x) ? max.x : x;
  2570. x = (x < min.x) ? min.x : x;
  2571. var y = value.y;
  2572. y = (y > max.y) ? max.y : y;
  2573. y = (y < min.y) ? min.y : y;
  2574. return new Vector2(x, y);
  2575. };
  2576. /**
  2577. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2578. * @param value1 defines the 1st control point
  2579. * @param tangent1 defines the outgoing tangent
  2580. * @param value2 defines the 2nd control point
  2581. * @param tangent2 defines the incoming tangent
  2582. * @param amount defines the interpolation factor
  2583. * @returns a new Vector2
  2584. */
  2585. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2586. var squared = amount * amount;
  2587. var cubed = amount * squared;
  2588. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2589. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2590. var part3 = (cubed - (2.0 * squared)) + amount;
  2591. var part4 = cubed - squared;
  2592. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2593. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2594. return new Vector2(x, y);
  2595. };
  2596. /**
  2597. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2598. * @param start defines the start vector
  2599. * @param end defines the end vector
  2600. * @param amount defines the interpolation factor
  2601. * @returns a new Vector2
  2602. */
  2603. Vector2.Lerp = function (start, end, amount) {
  2604. var x = start.x + ((end.x - start.x) * amount);
  2605. var y = start.y + ((end.y - start.y) * amount);
  2606. return new Vector2(x, y);
  2607. };
  2608. /**
  2609. * Gets the dot product of the vector "left" and the vector "right"
  2610. * @param left defines first vector
  2611. * @param right defines second vector
  2612. * @returns the dot product (float)
  2613. */
  2614. Vector2.Dot = function (left, right) {
  2615. return left.x * right.x + left.y * right.y;
  2616. };
  2617. /**
  2618. * Returns a new Vector2 equal to the normalized given vector
  2619. * @param vector defines the vector to normalize
  2620. * @returns a new Vector2
  2621. */
  2622. Vector2.Normalize = function (vector) {
  2623. var newVector = vector.clone();
  2624. newVector.normalize();
  2625. return newVector;
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2629. * @param left defines 1st vector
  2630. * @param right defines 2nd vector
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.Minimize = function (left, right) {
  2634. var x = (left.x < right.x) ? left.x : right.x;
  2635. var y = (left.y < right.y) ? left.y : right.y;
  2636. return new Vector2(x, y);
  2637. };
  2638. /**
  2639. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2640. * @param left defines 1st vector
  2641. * @param right defines 2nd vector
  2642. * @returns a new Vector2
  2643. */
  2644. Vector2.Maximize = function (left, right) {
  2645. var x = (left.x > right.x) ? left.x : right.x;
  2646. var y = (left.y > right.y) ? left.y : right.y;
  2647. return new Vector2(x, y);
  2648. };
  2649. /**
  2650. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2651. * @param vector defines the vector to transform
  2652. * @param transformation defines the matrix to apply
  2653. * @returns a new Vector2
  2654. */
  2655. Vector2.Transform = function (vector, transformation) {
  2656. var r = Vector2.Zero();
  2657. Vector2.TransformToRef(vector, transformation, r);
  2658. return r;
  2659. };
  2660. /**
  2661. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2662. * @param vector defines the vector to transform
  2663. * @param transformation defines the matrix to apply
  2664. * @param result defines the target vector
  2665. */
  2666. Vector2.TransformToRef = function (vector, transformation, result) {
  2667. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2668. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2669. result.x = x;
  2670. result.y = y;
  2671. };
  2672. /**
  2673. * Determines if a given vector is included in a triangle
  2674. * @param p defines the vector to test
  2675. * @param p0 defines 1st triangle point
  2676. * @param p1 defines 2nd triangle point
  2677. * @param p2 defines 3rd triangle point
  2678. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2679. */
  2680. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2681. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2682. var sign = a < 0 ? -1 : 1;
  2683. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2684. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2685. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2686. };
  2687. /**
  2688. * Gets the distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the distance between vectors
  2692. */
  2693. Vector2.Distance = function (value1, value2) {
  2694. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2695. };
  2696. /**
  2697. * Returns the squared distance between the vectors "value1" and "value2"
  2698. * @param value1 defines first vector
  2699. * @param value2 defines second vector
  2700. * @returns the squared distance between vectors
  2701. */
  2702. Vector2.DistanceSquared = function (value1, value2) {
  2703. var x = value1.x - value2.x;
  2704. var y = value1.y - value2.y;
  2705. return (x * x) + (y * y);
  2706. };
  2707. /**
  2708. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2709. * @param value1 defines first vector
  2710. * @param value2 defines second vector
  2711. * @returns a new Vector2
  2712. */
  2713. Vector2.Center = function (value1, value2) {
  2714. var center = value1.add(value2);
  2715. center.scaleInPlace(0.5);
  2716. return center;
  2717. };
  2718. /**
  2719. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2720. * @param p defines the middle point
  2721. * @param segA defines one point of the segment
  2722. * @param segB defines the other point of the segment
  2723. * @returns the shortest distance
  2724. */
  2725. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2726. var l2 = Vector2.DistanceSquared(segA, segB);
  2727. if (l2 === 0.0) {
  2728. return Vector2.Distance(p, segA);
  2729. }
  2730. var v = segB.subtract(segA);
  2731. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2732. var proj = segA.add(v.multiplyByFloats(t, t));
  2733. return Vector2.Distance(p, proj);
  2734. };
  2735. return Vector2;
  2736. }());
  2737. BABYLON.Vector2 = Vector2;
  2738. /**
  2739. * Classed used to store (x,y,z) vector representation
  2740. * A Vector3 is the main object used in 3D geometry
  2741. * It can represent etiher the coordinates of a point the space, either a direction
  2742. * Reminder: Babylon.js uses a left handed forward facing system
  2743. */
  2744. var Vector3 = /** @class */ (function () {
  2745. /**
  2746. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2747. * @param x defines the first coordinates (on X axis)
  2748. * @param y defines the second coordinates (on Y axis)
  2749. * @param z defines the third coordinates (on Z axis)
  2750. */
  2751. function Vector3(
  2752. /**
  2753. * Defines the first coordinates (on X axis)
  2754. */
  2755. x,
  2756. /**
  2757. * Defines the second coordinates (on Y axis)
  2758. */
  2759. y,
  2760. /**
  2761. * Defines the third coordinates (on Z axis)
  2762. */
  2763. z) {
  2764. if (x === void 0) { x = 0; }
  2765. if (y === void 0) { y = 0; }
  2766. if (z === void 0) { z = 0; }
  2767. this.x = x;
  2768. this.y = y;
  2769. this.z = z;
  2770. }
  2771. /**
  2772. * Creates a string representation of the Vector3
  2773. * @returns a string with the Vector3 coordinates.
  2774. */
  2775. Vector3.prototype.toString = function () {
  2776. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2777. };
  2778. /**
  2779. * Gets the class name
  2780. * @returns the string "Vector3"
  2781. */
  2782. Vector3.prototype.getClassName = function () {
  2783. return "Vector3";
  2784. };
  2785. /**
  2786. * Creates the Vector3 hash code
  2787. * @returns a number which tends to be unique between Vector3 instances
  2788. */
  2789. Vector3.prototype.getHashCode = function () {
  2790. var hash = this.x || 0;
  2791. hash = (hash * 397) ^ (this.y || 0);
  2792. hash = (hash * 397) ^ (this.z || 0);
  2793. return hash;
  2794. };
  2795. // Operators
  2796. /**
  2797. * Creates an array containing three elements : the coordinates of the Vector3
  2798. * @returns a new array of numbers
  2799. */
  2800. Vector3.prototype.asArray = function () {
  2801. var result = [];
  2802. this.toArray(result, 0);
  2803. return result;
  2804. };
  2805. /**
  2806. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2807. * @param array defines the destination array
  2808. * @param index defines the offset in the destination array
  2809. * @returns the current Vector3
  2810. */
  2811. Vector3.prototype.toArray = function (array, index) {
  2812. if (index === void 0) { index = 0; }
  2813. array[index] = this.x;
  2814. array[index + 1] = this.y;
  2815. array[index + 2] = this.z;
  2816. return this;
  2817. };
  2818. /**
  2819. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2820. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2821. */
  2822. Vector3.prototype.toQuaternion = function () {
  2823. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2824. };
  2825. /**
  2826. * Adds the given vector to the current Vector3
  2827. * @param otherVector defines the second operand
  2828. * @returns the current updated Vector3
  2829. */
  2830. Vector3.prototype.addInPlace = function (otherVector) {
  2831. this.x += otherVector.x;
  2832. this.y += otherVector.y;
  2833. this.z += otherVector.z;
  2834. return this;
  2835. };
  2836. /**
  2837. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2838. * @param otherVector defines the second operand
  2839. * @returns the resulting Vector3
  2840. */
  2841. Vector3.prototype.add = function (otherVector) {
  2842. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2843. };
  2844. /**
  2845. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2846. * @param otherVector defines the second operand
  2847. * @param result defines the Vector3 object where to store the result
  2848. * @returns the current Vector3
  2849. */
  2850. Vector3.prototype.addToRef = function (otherVector, result) {
  2851. result.x = this.x + otherVector.x;
  2852. result.y = this.y + otherVector.y;
  2853. result.z = this.z + otherVector.z;
  2854. return this;
  2855. };
  2856. /**
  2857. * Subtract the given vector from the current Vector3
  2858. * @param otherVector defines the second operand
  2859. * @returns the current updated Vector3
  2860. */
  2861. Vector3.prototype.subtractInPlace = function (otherVector) {
  2862. this.x -= otherVector.x;
  2863. this.y -= otherVector.y;
  2864. this.z -= otherVector.z;
  2865. return this;
  2866. };
  2867. /**
  2868. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2869. * @param otherVector defines the second operand
  2870. * @returns the resulting Vector3
  2871. */
  2872. Vector3.prototype.subtract = function (otherVector) {
  2873. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2874. };
  2875. /**
  2876. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2877. * @param otherVector defines the second operand
  2878. * @param result defines the Vector3 object where to store the result
  2879. * @returns the current Vector3
  2880. */
  2881. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2882. result.x = this.x - otherVector.x;
  2883. result.y = this.y - otherVector.y;
  2884. result.z = this.z - otherVector.z;
  2885. return this;
  2886. };
  2887. /**
  2888. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2889. * @param x defines the x coordinate of the operand
  2890. * @param y defines the y coordinate of the operand
  2891. * @param z defines the z coordinate of the operand
  2892. * @returns the resulting Vector3
  2893. */
  2894. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2895. return new Vector3(this.x - x, this.y - y, this.z - z);
  2896. };
  2897. /**
  2898. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2899. * @param x defines the x coordinate of the operand
  2900. * @param y defines the y coordinate of the operand
  2901. * @param z defines the z coordinate of the operand
  2902. * @param result defines the Vector3 object where to store the result
  2903. * @returns the current Vector3
  2904. */
  2905. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2906. result.x = this.x - x;
  2907. result.y = this.y - y;
  2908. result.z = this.z - z;
  2909. return this;
  2910. };
  2911. /**
  2912. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2913. * @returns a new Vector3
  2914. */
  2915. Vector3.prototype.negate = function () {
  2916. return new Vector3(-this.x, -this.y, -this.z);
  2917. };
  2918. /**
  2919. * Multiplies the Vector3 coordinates by the float "scale"
  2920. * @param scale defines the multiplier factor
  2921. * @returns the current updated Vector3
  2922. */
  2923. Vector3.prototype.scaleInPlace = function (scale) {
  2924. this.x *= scale;
  2925. this.y *= scale;
  2926. this.z *= scale;
  2927. return this;
  2928. };
  2929. /**
  2930. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2931. * @param scale defines the multiplier factor
  2932. * @returns a new Vector3
  2933. */
  2934. Vector3.prototype.scale = function (scale) {
  2935. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2936. };
  2937. /**
  2938. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2939. * @param scale defines the multiplier factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the current Vector3
  2942. */
  2943. Vector3.prototype.scaleToRef = function (scale, result) {
  2944. result.x = this.x * scale;
  2945. result.y = this.y * scale;
  2946. result.z = this.z * scale;
  2947. return this;
  2948. };
  2949. /**
  2950. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2951. * @param scale defines the scale factor
  2952. * @param result defines the Vector3 object where to store the result
  2953. * @returns the unmodified current Vector3
  2954. */
  2955. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2956. result.x += this.x * scale;
  2957. result.y += this.y * scale;
  2958. result.z += this.z * scale;
  2959. return this;
  2960. };
  2961. /**
  2962. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2963. * @param otherVector defines the second operand
  2964. * @returns true if both vectors are equals
  2965. */
  2966. Vector3.prototype.equals = function (otherVector) {
  2967. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2968. };
  2969. /**
  2970. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2971. * @param otherVector defines the second operand
  2972. * @param epsilon defines the minimal distance to define values as equals
  2973. * @returns true if both vectors are distant less than epsilon
  2974. */
  2975. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2976. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2977. 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);
  2978. };
  2979. /**
  2980. * Returns true if the current Vector3 coordinates equals the given floats
  2981. * @param x defines the x coordinate of the operand
  2982. * @param y defines the y coordinate of the operand
  2983. * @param z defines the z coordinate of the operand
  2984. * @returns true if both vectors are equals
  2985. */
  2986. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2987. return this.x === x && this.y === y && this.z === z;
  2988. };
  2989. /**
  2990. * Multiplies the current Vector3 coordinates by the given ones
  2991. * @param otherVector defines the second operand
  2992. * @returns the current updated Vector3
  2993. */
  2994. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2995. this.x *= otherVector.x;
  2996. this.y *= otherVector.y;
  2997. this.z *= otherVector.z;
  2998. return this;
  2999. };
  3000. /**
  3001. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3002. * @param otherVector defines the second operand
  3003. * @returns the new Vector3
  3004. */
  3005. Vector3.prototype.multiply = function (otherVector) {
  3006. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3007. };
  3008. /**
  3009. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3010. * @param otherVector defines the second operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3015. result.x = this.x * otherVector.x;
  3016. result.y = this.y * otherVector.y;
  3017. result.z = this.z * otherVector.z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3022. * @param x defines the x coordinate of the operand
  3023. * @param y defines the y coordinate of the operand
  3024. * @param z defines the z coordinate of the operand
  3025. * @returns the new Vector3
  3026. */
  3027. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3028. return new Vector3(this.x * x, this.y * y, this.z * z);
  3029. };
  3030. /**
  3031. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3032. * @param otherVector defines the second operand
  3033. * @returns the new Vector3
  3034. */
  3035. Vector3.prototype.divide = function (otherVector) {
  3036. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3040. * @param otherVector defines the second operand
  3041. * @param result defines the Vector3 object where to store the result
  3042. * @returns the current Vector3
  3043. */
  3044. Vector3.prototype.divideToRef = function (otherVector, result) {
  3045. result.x = this.x / otherVector.x;
  3046. result.y = this.y / otherVector.y;
  3047. result.z = this.z / otherVector.z;
  3048. return this;
  3049. };
  3050. /**
  3051. * Divides the current Vector3 coordinates by the given ones.
  3052. * @param otherVector defines the second operand
  3053. * @returns the current updated Vector3
  3054. */
  3055. Vector3.prototype.divideInPlace = function (otherVector) {
  3056. return this.divideToRef(otherVector, this);
  3057. };
  3058. /**
  3059. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3060. * @param other defines the second operand
  3061. * @returns the current updated Vector3
  3062. */
  3063. Vector3.prototype.minimizeInPlace = function (other) {
  3064. if (other.x < this.x)
  3065. this.x = other.x;
  3066. if (other.y < this.y)
  3067. this.y = other.y;
  3068. if (other.z < this.z)
  3069. this.z = other.z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3074. * @param other defines the second operand
  3075. * @returns the current updated Vector3
  3076. */
  3077. Vector3.prototype.maximizeInPlace = function (other) {
  3078. if (other.x > this.x)
  3079. this.x = other.x;
  3080. if (other.y > this.y)
  3081. this.y = other.y;
  3082. if (other.z > this.z)
  3083. this.z = other.z;
  3084. return this;
  3085. };
  3086. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3087. /**
  3088. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3089. */
  3090. get: function () {
  3091. var absX = Math.abs(this.x);
  3092. var absY = Math.abs(this.y);
  3093. if (absX !== absY) {
  3094. return true;
  3095. }
  3096. var absZ = Math.abs(this.z);
  3097. if (absX !== absZ) {
  3098. return true;
  3099. }
  3100. if (absY !== absZ) {
  3101. return true;
  3102. }
  3103. return false;
  3104. },
  3105. enumerable: true,
  3106. configurable: true
  3107. });
  3108. // Properties
  3109. /**
  3110. * Gets the length of the Vector3
  3111. * @returns the length of the Vecto3
  3112. */
  3113. Vector3.prototype.length = function () {
  3114. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3115. };
  3116. /**
  3117. * Gets the squared length of the Vector3
  3118. * @returns squared length of the Vector3
  3119. */
  3120. Vector3.prototype.lengthSquared = function () {
  3121. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3122. };
  3123. /**
  3124. * Normalize the current Vector3.
  3125. * Please note that this is an in place operation.
  3126. * @returns the current updated Vector3
  3127. */
  3128. Vector3.prototype.normalize = function () {
  3129. var len = this.length();
  3130. if (len === 0 || len === 1.0)
  3131. return this;
  3132. var num = 1.0 / len;
  3133. this.x *= num;
  3134. this.y *= num;
  3135. this.z *= num;
  3136. return this;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to a new vector
  3140. * @returns the new Vector3
  3141. */
  3142. Vector3.prototype.normalizeToNew = function () {
  3143. var normalized = new Vector3(0, 0, 0);
  3144. this.normalizeToRef(normalized);
  3145. return normalized;
  3146. };
  3147. /**
  3148. * Normalize the current Vector3 to the reference
  3149. * @param reference define the Vector3 to update
  3150. * @returns the updated Vector3
  3151. */
  3152. Vector3.prototype.normalizeToRef = function (reference) {
  3153. var len = this.length();
  3154. if (len === 0 || len === 1.0) {
  3155. reference.set(this.x, this.y, this.z);
  3156. return reference;
  3157. }
  3158. var scale = 1.0 / len;
  3159. this.scaleToRef(scale, reference);
  3160. return reference;
  3161. };
  3162. /**
  3163. * Creates a new Vector3 copied from the current Vector3
  3164. * @returns the new Vector3
  3165. */
  3166. Vector3.prototype.clone = function () {
  3167. return new Vector3(this.x, this.y, this.z);
  3168. };
  3169. /**
  3170. * Copies the given vector coordinates to the current Vector3 ones
  3171. * @param source defines the source Vector3
  3172. * @returns the current updated Vector3
  3173. */
  3174. Vector3.prototype.copyFrom = function (source) {
  3175. this.x = source.x;
  3176. this.y = source.y;
  3177. this.z = source.z;
  3178. return this;
  3179. };
  3180. /**
  3181. * Copies the given floats to the current Vector3 coordinates
  3182. * @param x defines the x coordinate of the operand
  3183. * @param y defines the y coordinate of the operand
  3184. * @param z defines the z coordinate of the operand
  3185. * @returns the current updated Vector3
  3186. */
  3187. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3188. this.x = x;
  3189. this.y = y;
  3190. this.z = z;
  3191. return this;
  3192. };
  3193. /**
  3194. * Copies the given floats to the current Vector3 coordinates
  3195. * @param x defines the x coordinate of the operand
  3196. * @param y defines the y coordinate of the operand
  3197. * @param z defines the z coordinate of the operand
  3198. * @returns the current updated Vector3
  3199. */
  3200. Vector3.prototype.set = function (x, y, z) {
  3201. return this.copyFromFloats(x, y, z);
  3202. };
  3203. // Statics
  3204. /**
  3205. * Get the clip factor between two vectors
  3206. * @param vector0 defines the first operand
  3207. * @param vector1 defines the second operand
  3208. * @param axis defines the axis to use
  3209. * @param size defines the size along the axis
  3210. * @returns the clip factor
  3211. */
  3212. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3213. var d0 = Vector3.Dot(vector0, axis) - size;
  3214. var d1 = Vector3.Dot(vector1, axis) - size;
  3215. var s = d0 / (d0 - d1);
  3216. return s;
  3217. };
  3218. /**
  3219. * Get angle between two vectors
  3220. * @param vector0 angle between vector0 and vector1
  3221. * @param vector1 angle between vector0 and vector1
  3222. * @param normal direction of the normal
  3223. * @return the angle between vector0 and vector1
  3224. */
  3225. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3226. var v0 = vector0.clone().normalize();
  3227. var v1 = vector1.clone().normalize();
  3228. var dot = Vector3.Dot(v0, v1);
  3229. var n = Vector3.Cross(v0, v1);
  3230. if (Vector3.Dot(n, normal) > 0) {
  3231. return Math.acos(dot);
  3232. }
  3233. return -Math.acos(dot);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given array
  3237. * @param array defines the source array
  3238. * @param offset defines the offset in the source array
  3239. * @returns the new Vector3
  3240. */
  3241. Vector3.FromArray = function (array, offset) {
  3242. if (!offset) {
  3243. offset = 0;
  3244. }
  3245. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3246. };
  3247. /**
  3248. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3249. * This function is deprecated. Use FromArray instead
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @returns the new Vector3
  3253. */
  3254. Vector3.FromFloatArray = function (array, offset) {
  3255. return Vector3.FromArray(array, offset);
  3256. };
  3257. /**
  3258. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3259. * @param array defines the source array
  3260. * @param offset defines the offset in the source array
  3261. * @param result defines the Vector3 where to store the result
  3262. */
  3263. Vector3.FromArrayToRef = function (array, offset, result) {
  3264. result.x = array[offset];
  3265. result.y = array[offset + 1];
  3266. result.z = array[offset + 2];
  3267. };
  3268. /**
  3269. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3270. * This function is deprecated. Use FromArrayToRef instead.
  3271. * @param array defines the source array
  3272. * @param offset defines the offset in the source array
  3273. * @param result defines the Vector3 where to store the result
  3274. */
  3275. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3276. return Vector3.FromArrayToRef(array, offset, result);
  3277. };
  3278. /**
  3279. * Sets the given vector "result" with the given floats.
  3280. * @param x defines the x coordinate of the source
  3281. * @param y defines the y coordinate of the source
  3282. * @param z defines the z coordinate of the source
  3283. * @param result defines the Vector3 where to store the result
  3284. */
  3285. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3286. result.x = x;
  3287. result.y = y;
  3288. result.z = z;
  3289. };
  3290. /**
  3291. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3292. * @returns a new empty Vector3
  3293. */
  3294. Vector3.Zero = function () {
  3295. return new Vector3(0.0, 0.0, 0.0);
  3296. };
  3297. /**
  3298. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3299. * @returns a new unit Vector3
  3300. */
  3301. Vector3.One = function () {
  3302. return new Vector3(1.0, 1.0, 1.0);
  3303. };
  3304. /**
  3305. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3306. * @returns a new up Vector3
  3307. */
  3308. Vector3.Up = function () {
  3309. return new Vector3(0.0, 1.0, 0.0);
  3310. };
  3311. /**
  3312. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3313. * @returns a new down Vector3
  3314. */
  3315. Vector3.Down = function () {
  3316. return new Vector3(0.0, -1.0, 0.0);
  3317. };
  3318. /**
  3319. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3320. * @returns a new forward Vector3
  3321. */
  3322. Vector3.Forward = function () {
  3323. return new Vector3(0.0, 0.0, 1.0);
  3324. };
  3325. /**
  3326. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3327. * @returns a new right Vector3
  3328. */
  3329. Vector3.Right = function () {
  3330. return new Vector3(1.0, 0.0, 0.0);
  3331. };
  3332. /**
  3333. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3334. * @returns a new left Vector3
  3335. */
  3336. Vector3.Left = function () {
  3337. return new Vector3(-1.0, 0.0, 0.0);
  3338. };
  3339. /**
  3340. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3341. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3342. * @param vector defines the Vector3 to transform
  3343. * @param transformation defines the transformation matrix
  3344. * @returns the transformed Vector3
  3345. */
  3346. Vector3.TransformCoordinates = function (vector, transformation) {
  3347. var result = Vector3.Zero();
  3348. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3349. return result;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3353. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3354. * @param vector defines the Vector3 to transform
  3355. * @param transformation defines the transformation matrix
  3356. * @param result defines the Vector3 where to store the result
  3357. */
  3358. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3359. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3360. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3361. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3362. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3363. result.x = x / w;
  3364. result.y = y / w;
  3365. result.z = z / w;
  3366. };
  3367. /**
  3368. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3369. * This method computes tranformed coordinates only, not transformed direction vectors
  3370. * @param x define the x coordinate of the source vector
  3371. * @param y define the y coordinate of the source vector
  3372. * @param z define the z coordinate of the source vector
  3373. * @param transformation defines the transformation matrix
  3374. * @param result defines the Vector3 where to store the result
  3375. */
  3376. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3377. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3378. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3379. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3380. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3381. result.x = rx / rw;
  3382. result.y = ry / rw;
  3383. result.z = rz / rw;
  3384. };
  3385. /**
  3386. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3387. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3388. * @param vector defines the Vector3 to transform
  3389. * @param transformation defines the transformation matrix
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.TransformNormal = function (vector, transformation) {
  3393. var result = Vector3.Zero();
  3394. Vector3.TransformNormalToRef(vector, transformation, result);
  3395. return result;
  3396. };
  3397. /**
  3398. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3399. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3400. * @param vector defines the Vector3 to transform
  3401. * @param transformation defines the transformation matrix
  3402. * @param result defines the Vector3 where to store the result
  3403. */
  3404. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3408. result.x = x;
  3409. result.y = y;
  3410. result.z = z;
  3411. };
  3412. /**
  3413. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3414. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3415. * @param x define the x coordinate of the source vector
  3416. * @param y define the y coordinate of the source vector
  3417. * @param z define the z coordinate of the source vector
  3418. * @param transformation defines the transformation matrix
  3419. * @param result defines the Vector3 where to store the result
  3420. */
  3421. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3422. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3423. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3424. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3425. };
  3426. /**
  3427. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3428. * @param value1 defines the first control point
  3429. * @param value2 defines the second control point
  3430. * @param value3 defines the third control point
  3431. * @param value4 defines the fourth control point
  3432. * @param amount defines the amount on the spline to use
  3433. * @returns the new Vector3
  3434. */
  3435. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3436. var squared = amount * amount;
  3437. var cubed = amount * squared;
  3438. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3439. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3440. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3441. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3442. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3443. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3444. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3445. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3446. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3447. return new Vector3(x, y, z);
  3448. };
  3449. /**
  3450. * 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"
  3451. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3452. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3453. * @param value defines the current value
  3454. * @param min defines the lower range value
  3455. * @param max defines the upper range value
  3456. * @returns the new Vector3
  3457. */
  3458. Vector3.Clamp = function (value, min, max) {
  3459. var x = value.x;
  3460. x = (x > max.x) ? max.x : x;
  3461. x = (x < min.x) ? min.x : x;
  3462. var y = value.y;
  3463. y = (y > max.y) ? max.y : y;
  3464. y = (y < min.y) ? min.y : y;
  3465. var z = value.z;
  3466. z = (z > max.z) ? max.z : z;
  3467. z = (z < min.z) ? min.z : z;
  3468. return new Vector3(x, y, z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3472. * @param value1 defines the first control point
  3473. * @param tangent1 defines the first tangent vector
  3474. * @param value2 defines the second control point
  3475. * @param tangent2 defines the second tangent vector
  3476. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3480. var squared = amount * amount;
  3481. var cubed = amount * squared;
  3482. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3483. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3484. var part3 = (cubed - (2.0 * squared)) + amount;
  3485. var part4 = cubed - squared;
  3486. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3487. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3488. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3489. return new Vector3(x, y, z);
  3490. };
  3491. /**
  3492. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3493. * @param start defines the start value
  3494. * @param end defines the end value
  3495. * @param amount max defines amount between both (between 0 and 1)
  3496. * @returns the new Vector3
  3497. */
  3498. Vector3.Lerp = function (start, end, amount) {
  3499. var result = new Vector3(0, 0, 0);
  3500. Vector3.LerpToRef(start, end, amount, result);
  3501. return result;
  3502. };
  3503. /**
  3504. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3505. * @param start defines the start value
  3506. * @param end defines the end value
  3507. * @param amount max defines amount between both (between 0 and 1)
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.LerpToRef = function (start, end, amount, result) {
  3511. result.x = start.x + ((end.x - start.x) * amount);
  3512. result.y = start.y + ((end.y - start.y) * amount);
  3513. result.z = start.z + ((end.z - start.z) * amount);
  3514. };
  3515. /**
  3516. * Returns the dot product (float) between the vectors "left" and "right"
  3517. * @param left defines the left operand
  3518. * @param right defines the right operand
  3519. * @returns the dot product
  3520. */
  3521. Vector3.Dot = function (left, right) {
  3522. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3523. };
  3524. /**
  3525. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3526. * The cross product is then orthogonal to both "left" and "right"
  3527. * @param left defines the left operand
  3528. * @param right defines the right operand
  3529. * @returns the cross product
  3530. */
  3531. Vector3.Cross = function (left, right) {
  3532. var result = Vector3.Zero();
  3533. Vector3.CrossToRef(left, right, result);
  3534. return result;
  3535. };
  3536. /**
  3537. * Sets the given vector "result" with the cross product of "left" and "right"
  3538. * The cross product is then orthogonal to both "left" and "right"
  3539. * @param left defines the left operand
  3540. * @param right defines the right operand
  3541. * @param result defines the Vector3 where to store the result
  3542. */
  3543. Vector3.CrossToRef = function (left, right, result) {
  3544. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3545. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3546. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3547. result.copyFrom(MathTmp.Vector3[0]);
  3548. };
  3549. /**
  3550. * Returns a new Vector3 as the normalization of the given vector
  3551. * @param vector defines the Vector3 to normalize
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Normalize = function (vector) {
  3555. var result = Vector3.Zero();
  3556. Vector3.NormalizeToRef(vector, result);
  3557. return result;
  3558. };
  3559. /**
  3560. * Sets the given vector "result" with the normalization of the given first vector
  3561. * @param vector defines the Vector3 to normalize
  3562. * @param result defines the Vector3 where to store the result
  3563. */
  3564. Vector3.NormalizeToRef = function (vector, result) {
  3565. result.copyFrom(vector);
  3566. result.normalize();
  3567. };
  3568. /**
  3569. * Project a Vector3 onto screen space
  3570. * @param vector defines the Vector3 to project
  3571. * @param world defines the world matrix to use
  3572. * @param transform defines the transform (view x projection) matrix to use
  3573. * @param viewport defines the screen viewport to use
  3574. * @returns the new Vector3
  3575. */
  3576. Vector3.Project = function (vector, world, transform, viewport) {
  3577. var cw = viewport.width;
  3578. var ch = viewport.height;
  3579. var cx = viewport.x;
  3580. var cy = viewport.y;
  3581. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3582. 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);
  3583. var matrix = MathTmp.Matrix[0];
  3584. world.multiplyToRef(transform, matrix);
  3585. matrix.multiplyToRef(viewportMatrix, matrix);
  3586. return Vector3.TransformCoordinates(vector, matrix);
  3587. };
  3588. /**
  3589. * Unproject from screen space to object space
  3590. * @param source defines the screen space Vector3 to use
  3591. * @param viewportWidth defines the current width of the viewport
  3592. * @param viewportHeight defines the current height of the viewport
  3593. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3594. * @param transform defines the transform (view x projection) matrix to use
  3595. * @returns the new Vector3
  3596. */
  3597. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3598. var matrix = MathTmp.Matrix[0];
  3599. world.multiplyToRef(transform, matrix);
  3600. matrix.invert();
  3601. source.x = source.x / viewportWidth * 2 - 1;
  3602. source.y = -(source.y / viewportHeight * 2 - 1);
  3603. var vector = Vector3.TransformCoordinates(source, matrix);
  3604. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3605. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3606. vector = vector.scale(1.0 / num);
  3607. }
  3608. return vector;
  3609. };
  3610. /**
  3611. * Unproject from screen space to object space
  3612. * @param source defines the screen space Vector3 to use
  3613. * @param viewportWidth defines the current width of the viewport
  3614. * @param viewportHeight defines the current height of the viewport
  3615. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3616. * @param view defines the view matrix to use
  3617. * @param projection defines the projection matrix to use
  3618. * @returns the new Vector3
  3619. */
  3620. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3621. var result = Vector3.Zero();
  3622. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3623. return result;
  3624. };
  3625. /**
  3626. * Unproject from screen space to object space
  3627. * @param source defines the screen space Vector3 to use
  3628. * @param viewportWidth defines the current width of the viewport
  3629. * @param viewportHeight defines the current height of the viewport
  3630. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3631. * @param view defines the view matrix to use
  3632. * @param projection defines the projection matrix to use
  3633. * @param result defines the Vector3 where to store the result
  3634. */
  3635. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3636. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3637. };
  3638. /**
  3639. * Unproject from screen space to object space
  3640. * @param sourceX defines the screen space x coordinate to use
  3641. * @param sourceY defines the screen space y coordinate to use
  3642. * @param sourceZ defines the screen space z coordinate to use
  3643. * @param viewportWidth defines the current width of the viewport
  3644. * @param viewportHeight defines the current height of the viewport
  3645. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3646. * @param view defines the view matrix to use
  3647. * @param projection defines the projection matrix to use
  3648. * @param result defines the Vector3 where to store the result
  3649. */
  3650. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3651. var matrix = MathTmp.Matrix[0];
  3652. world.multiplyToRef(view, matrix);
  3653. matrix.multiplyToRef(projection, matrix);
  3654. matrix.invert();
  3655. var screenSource = MathTmp.Vector3[0];
  3656. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3657. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3658. screenSource.z = 2 * sourceZ - 1.0;
  3659. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3660. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3661. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3662. result.scaleInPlace(1.0 / num);
  3663. }
  3664. };
  3665. /**
  3666. * Gets the minimal coordinate values between two Vector3
  3667. * @param left defines the first operand
  3668. * @param right defines the second operand
  3669. * @returns the new Vector3
  3670. */
  3671. Vector3.Minimize = function (left, right) {
  3672. var min = left.clone();
  3673. min.minimizeInPlace(right);
  3674. return min;
  3675. };
  3676. /**
  3677. * Gets the maximal coordinate values between two Vector3
  3678. * @param left defines the first operand
  3679. * @param right defines the second operand
  3680. * @returns the new Vector3
  3681. */
  3682. Vector3.Maximize = function (left, right) {
  3683. var max = left.clone();
  3684. max.maximizeInPlace(right);
  3685. return max;
  3686. };
  3687. /**
  3688. * Returns the distance between the vectors "value1" and "value2"
  3689. * @param value1 defines the first operand
  3690. * @param value2 defines the second operand
  3691. * @returns the distance
  3692. */
  3693. Vector3.Distance = function (value1, value2) {
  3694. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3695. };
  3696. /**
  3697. * Returns the squared distance between the vectors "value1" and "value2"
  3698. * @param value1 defines the first operand
  3699. * @param value2 defines the second operand
  3700. * @returns the squared distance
  3701. */
  3702. Vector3.DistanceSquared = function (value1, value2) {
  3703. var x = value1.x - value2.x;
  3704. var y = value1.y - value2.y;
  3705. var z = value1.z - value2.z;
  3706. return (x * x) + (y * y) + (z * z);
  3707. };
  3708. /**
  3709. * Returns a new Vector3 located at the center between "value1" and "value2"
  3710. * @param value1 defines the first operand
  3711. * @param value2 defines the second operand
  3712. * @returns the new Vector3
  3713. */
  3714. Vector3.Center = function (value1, value2) {
  3715. var center = value1.add(value2);
  3716. center.scaleInPlace(0.5);
  3717. return center;
  3718. };
  3719. /**
  3720. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3721. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3722. * to something in order to rotate it from its local system to the given target system
  3723. * Note: axis1, axis2 and axis3 are normalized during this operation
  3724. * @param axis1 defines the first axis
  3725. * @param axis2 defines the second axis
  3726. * @param axis3 defines the third axis
  3727. * @returns a new Vector3
  3728. */
  3729. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3730. var rotation = Vector3.Zero();
  3731. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3732. return rotation;
  3733. };
  3734. /**
  3735. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3736. * @param axis1 defines the first axis
  3737. * @param axis2 defines the second axis
  3738. * @param axis3 defines the third axis
  3739. * @param ref defines the Vector3 where to store the result
  3740. */
  3741. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3742. var quat = MathTmp.Quaternion[0];
  3743. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3744. quat.toEulerAnglesToRef(ref);
  3745. };
  3746. return Vector3;
  3747. }());
  3748. BABYLON.Vector3 = Vector3;
  3749. //Vector4 class created for EulerAngle class conversion to Quaternion
  3750. var Vector4 = /** @class */ (function () {
  3751. /**
  3752. * Creates a Vector4 object from the given floats.
  3753. */
  3754. function Vector4(x, y, z, w) {
  3755. this.x = x;
  3756. this.y = y;
  3757. this.z = z;
  3758. this.w = w;
  3759. }
  3760. /**
  3761. * Returns the string with the Vector4 coordinates.
  3762. */
  3763. Vector4.prototype.toString = function () {
  3764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3765. };
  3766. /**
  3767. * Returns the string "Vector4".
  3768. */
  3769. Vector4.prototype.getClassName = function () {
  3770. return "Vector4";
  3771. };
  3772. /**
  3773. * Returns the Vector4 hash code.
  3774. */
  3775. Vector4.prototype.getHashCode = function () {
  3776. var hash = this.x || 0;
  3777. hash = (hash * 397) ^ (this.y || 0);
  3778. hash = (hash * 397) ^ (this.z || 0);
  3779. hash = (hash * 397) ^ (this.w || 0);
  3780. return hash;
  3781. };
  3782. // Operators
  3783. /**
  3784. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3785. */
  3786. Vector4.prototype.asArray = function () {
  3787. var result = new Array();
  3788. this.toArray(result, 0);
  3789. return result;
  3790. };
  3791. /**
  3792. * Populates the given array from the given index with the Vector4 coordinates.
  3793. * Returns the Vector4.
  3794. */
  3795. Vector4.prototype.toArray = function (array, index) {
  3796. if (index === undefined) {
  3797. index = 0;
  3798. }
  3799. array[index] = this.x;
  3800. array[index + 1] = this.y;
  3801. array[index + 2] = this.z;
  3802. array[index + 3] = this.w;
  3803. return this;
  3804. };
  3805. /**
  3806. * Adds the given vector to the current Vector4.
  3807. * Returns the updated Vector4.
  3808. */
  3809. Vector4.prototype.addInPlace = function (otherVector) {
  3810. this.x += otherVector.x;
  3811. this.y += otherVector.y;
  3812. this.z += otherVector.z;
  3813. this.w += otherVector.w;
  3814. return this;
  3815. };
  3816. /**
  3817. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3818. */
  3819. Vector4.prototype.add = function (otherVector) {
  3820. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3821. };
  3822. /**
  3823. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3824. * Returns the current Vector4.
  3825. */
  3826. Vector4.prototype.addToRef = function (otherVector, result) {
  3827. result.x = this.x + otherVector.x;
  3828. result.y = this.y + otherVector.y;
  3829. result.z = this.z + otherVector.z;
  3830. result.w = this.w + otherVector.w;
  3831. return this;
  3832. };
  3833. /**
  3834. * Subtract in place the given vector from the current Vector4.
  3835. * Returns the updated Vector4.
  3836. */
  3837. Vector4.prototype.subtractInPlace = function (otherVector) {
  3838. this.x -= otherVector.x;
  3839. this.y -= otherVector.y;
  3840. this.z -= otherVector.z;
  3841. this.w -= otherVector.w;
  3842. return this;
  3843. };
  3844. /**
  3845. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3846. */
  3847. Vector4.prototype.subtract = function (otherVector) {
  3848. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3849. };
  3850. /**
  3851. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3852. * Returns the current Vector4.
  3853. */
  3854. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3855. result.x = this.x - otherVector.x;
  3856. result.y = this.y - otherVector.y;
  3857. result.z = this.z - otherVector.z;
  3858. result.w = this.w - otherVector.w;
  3859. return this;
  3860. };
  3861. /**
  3862. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3863. */
  3864. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3865. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3866. };
  3867. /**
  3868. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3869. * Returns the current Vector4.
  3870. */
  3871. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3872. result.x = this.x - x;
  3873. result.y = this.y - y;
  3874. result.z = this.z - z;
  3875. result.w = this.w - w;
  3876. return this;
  3877. };
  3878. /**
  3879. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3880. */
  3881. Vector4.prototype.negate = function () {
  3882. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3883. };
  3884. /**
  3885. * Multiplies the current Vector4 coordinates by scale (float).
  3886. * Returns the updated Vector4.
  3887. */
  3888. Vector4.prototype.scaleInPlace = function (scale) {
  3889. this.x *= scale;
  3890. this.y *= scale;
  3891. this.z *= scale;
  3892. this.w *= scale;
  3893. return this;
  3894. };
  3895. /**
  3896. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3897. */
  3898. Vector4.prototype.scale = function (scale) {
  3899. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3900. };
  3901. /**
  3902. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3903. * Returns the current Vector4.
  3904. */
  3905. Vector4.prototype.scaleToRef = function (scale, result) {
  3906. result.x = this.x * scale;
  3907. result.y = this.y * scale;
  3908. result.z = this.z * scale;
  3909. result.w = this.w * scale;
  3910. return this;
  3911. };
  3912. /**
  3913. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3914. * @param scale defines the scale factor
  3915. * @param result defines the Vector4 object where to store the result
  3916. * @returns the unmodified current Vector4
  3917. */
  3918. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3919. result.x += this.x * scale;
  3920. result.y += this.y * scale;
  3921. result.z += this.z * scale;
  3922. result.w += this.w * scale;
  3923. return this;
  3924. };
  3925. /**
  3926. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3927. */
  3928. Vector4.prototype.equals = function (otherVector) {
  3929. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3930. };
  3931. /**
  3932. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3933. */
  3934. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3935. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3936. return otherVector
  3937. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3938. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3939. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3940. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3941. };
  3942. /**
  3943. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3944. */
  3945. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3946. return this.x === x && this.y === y && this.z === z && this.w === w;
  3947. };
  3948. /**
  3949. * Multiplies in place the current Vector4 by the given one.
  3950. * Returns the updated Vector4.
  3951. */
  3952. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3953. this.x *= otherVector.x;
  3954. this.y *= otherVector.y;
  3955. this.z *= otherVector.z;
  3956. this.w *= otherVector.w;
  3957. return this;
  3958. };
  3959. /**
  3960. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3961. */
  3962. Vector4.prototype.multiply = function (otherVector) {
  3963. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3964. };
  3965. /**
  3966. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3967. * Returns the current Vector4.
  3968. */
  3969. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3970. result.x = this.x * otherVector.x;
  3971. result.y = this.y * otherVector.y;
  3972. result.z = this.z * otherVector.z;
  3973. result.w = this.w * otherVector.w;
  3974. return this;
  3975. };
  3976. /**
  3977. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3978. */
  3979. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3980. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3981. };
  3982. /**
  3983. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3984. */
  3985. Vector4.prototype.divide = function (otherVector) {
  3986. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3987. };
  3988. /**
  3989. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3990. * Returns the current Vector4.
  3991. */
  3992. Vector4.prototype.divideToRef = function (otherVector, result) {
  3993. result.x = this.x / otherVector.x;
  3994. result.y = this.y / otherVector.y;
  3995. result.z = this.z / otherVector.z;
  3996. result.w = this.w / otherVector.w;
  3997. return this;
  3998. };
  3999. /**
  4000. * Divides the current Vector3 coordinates by the given ones.
  4001. * @returns the updated Vector3.
  4002. */
  4003. Vector4.prototype.divideInPlace = function (otherVector) {
  4004. return this.divideToRef(otherVector, this);
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.minimizeInPlace = function (other) {
  4012. if (other.x < this.x)
  4013. this.x = other.x;
  4014. if (other.y < this.y)
  4015. this.y = other.y;
  4016. if (other.z < this.z)
  4017. this.z = other.z;
  4018. if (other.w < this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. /**
  4023. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4024. * @param other defines the second operand
  4025. * @returns the current updated Vector4
  4026. */
  4027. Vector4.prototype.maximizeInPlace = function (other) {
  4028. if (other.x > this.x)
  4029. this.x = other.x;
  4030. if (other.y > this.y)
  4031. this.y = other.y;
  4032. if (other.z > this.z)
  4033. this.z = other.z;
  4034. if (other.w > this.w)
  4035. this.w = other.w;
  4036. return this;
  4037. };
  4038. // Properties
  4039. /**
  4040. * Returns the Vector4 length (float).
  4041. */
  4042. Vector4.prototype.length = function () {
  4043. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4044. };
  4045. /**
  4046. * Returns the Vector4 squared length (float).
  4047. */
  4048. Vector4.prototype.lengthSquared = function () {
  4049. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4050. };
  4051. // Methods
  4052. /**
  4053. * Normalizes in place the Vector4.
  4054. * Returns the updated Vector4.
  4055. */
  4056. Vector4.prototype.normalize = function () {
  4057. var len = this.length();
  4058. if (len === 0)
  4059. return this;
  4060. var num = 1.0 / len;
  4061. this.x *= num;
  4062. this.y *= num;
  4063. this.z *= num;
  4064. this.w *= num;
  4065. return this;
  4066. };
  4067. /**
  4068. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4069. */
  4070. Vector4.prototype.toVector3 = function () {
  4071. return new Vector3(this.x, this.y, this.z);
  4072. };
  4073. /**
  4074. * Returns a new Vector4 copied from the current one.
  4075. */
  4076. Vector4.prototype.clone = function () {
  4077. return new Vector4(this.x, this.y, this.z, this.w);
  4078. };
  4079. /**
  4080. * Updates the current Vector4 with the given one coordinates.
  4081. * Returns the updated Vector4.
  4082. */
  4083. Vector4.prototype.copyFrom = function (source) {
  4084. this.x = source.x;
  4085. this.y = source.y;
  4086. this.z = source.z;
  4087. this.w = source.w;
  4088. return this;
  4089. };
  4090. /**
  4091. * Updates the current Vector4 coordinates with the given floats.
  4092. * Returns the updated Vector4.
  4093. */
  4094. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4095. this.x = x;
  4096. this.y = y;
  4097. this.z = z;
  4098. this.w = w;
  4099. return this;
  4100. };
  4101. /**
  4102. * Updates the current Vector4 coordinates with the given floats.
  4103. * Returns the updated Vector4.
  4104. */
  4105. Vector4.prototype.set = function (x, y, z, w) {
  4106. return this.copyFromFloats(x, y, z, w);
  4107. };
  4108. // Statics
  4109. /**
  4110. * Returns a new Vector4 set from the starting index of the given array.
  4111. */
  4112. Vector4.FromArray = function (array, offset) {
  4113. if (!offset) {
  4114. offset = 0;
  4115. }
  4116. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4117. };
  4118. /**
  4119. * Updates the given vector "result" from the starting index of the given array.
  4120. */
  4121. Vector4.FromArrayToRef = function (array, offset, result) {
  4122. result.x = array[offset];
  4123. result.y = array[offset + 1];
  4124. result.z = array[offset + 2];
  4125. result.w = array[offset + 3];
  4126. };
  4127. /**
  4128. * Updates the given vector "result" from the starting index of the given Float32Array.
  4129. */
  4130. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4131. Vector4.FromArrayToRef(array, offset, result);
  4132. };
  4133. /**
  4134. * Updates the given vector "result" coordinates from the given floats.
  4135. */
  4136. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4137. result.x = x;
  4138. result.y = y;
  4139. result.z = z;
  4140. result.w = w;
  4141. };
  4142. /**
  4143. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4144. */
  4145. Vector4.Zero = function () {
  4146. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4147. };
  4148. /**
  4149. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4150. */
  4151. Vector4.One = function () {
  4152. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4153. };
  4154. /**
  4155. * Returns a new normalized Vector4 from the given one.
  4156. */
  4157. Vector4.Normalize = function (vector) {
  4158. var result = Vector4.Zero();
  4159. Vector4.NormalizeToRef(vector, result);
  4160. return result;
  4161. };
  4162. /**
  4163. * Updates the given vector "result" from the normalization of the given one.
  4164. */
  4165. Vector4.NormalizeToRef = function (vector, result) {
  4166. result.copyFrom(vector);
  4167. result.normalize();
  4168. };
  4169. Vector4.Minimize = function (left, right) {
  4170. var min = left.clone();
  4171. min.minimizeInPlace(right);
  4172. return min;
  4173. };
  4174. Vector4.Maximize = function (left, right) {
  4175. var max = left.clone();
  4176. max.maximizeInPlace(right);
  4177. return max;
  4178. };
  4179. /**
  4180. * Returns the distance (float) between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Distance = function (value1, value2) {
  4183. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4184. };
  4185. /**
  4186. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4187. */
  4188. Vector4.DistanceSquared = function (value1, value2) {
  4189. var x = value1.x - value2.x;
  4190. var y = value1.y - value2.y;
  4191. var z = value1.z - value2.z;
  4192. var w = value1.w - value2.w;
  4193. return (x * x) + (y * y) + (z * z) + (w * w);
  4194. };
  4195. /**
  4196. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4197. */
  4198. Vector4.Center = function (value1, value2) {
  4199. var center = value1.add(value2);
  4200. center.scaleInPlace(0.5);
  4201. return center;
  4202. };
  4203. /**
  4204. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4205. * This methods computes transformed normalized direction vectors only.
  4206. */
  4207. Vector4.TransformNormal = function (vector, transformation) {
  4208. var result = Vector4.Zero();
  4209. Vector4.TransformNormalToRef(vector, transformation, result);
  4210. return result;
  4211. };
  4212. /**
  4213. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4214. * This methods computes transformed normalized direction vectors only.
  4215. */
  4216. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4217. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4218. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4219. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4220. result.x = x;
  4221. result.y = y;
  4222. result.z = z;
  4223. result.w = vector.w;
  4224. };
  4225. /**
  4226. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4227. * This methods computes transformed normalized direction vectors only.
  4228. */
  4229. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4230. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4231. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4232. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4233. result.w = w;
  4234. };
  4235. return Vector4;
  4236. }());
  4237. BABYLON.Vector4 = Vector4;
  4238. var Size = /** @class */ (function () {
  4239. /**
  4240. * Creates a Size object from the given width and height (floats).
  4241. */
  4242. function Size(width, height) {
  4243. this.width = width;
  4244. this.height = height;
  4245. }
  4246. // Returns a string with the Size width and height.
  4247. Size.prototype.toString = function () {
  4248. return "{W: " + this.width + ", H: " + this.height + "}";
  4249. };
  4250. /**
  4251. * Returns the string "Size"
  4252. */
  4253. Size.prototype.getClassName = function () {
  4254. return "Size";
  4255. };
  4256. /**
  4257. * Returns the Size hash code.
  4258. */
  4259. Size.prototype.getHashCode = function () {
  4260. var hash = this.width || 0;
  4261. hash = (hash * 397) ^ (this.height || 0);
  4262. return hash;
  4263. };
  4264. /**
  4265. * Updates the current size from the given one.
  4266. * Returns the updated Size.
  4267. */
  4268. Size.prototype.copyFrom = function (src) {
  4269. this.width = src.width;
  4270. this.height = src.height;
  4271. };
  4272. /**
  4273. * Updates in place the current Size from the given floats.
  4274. * Returns the updated Size.
  4275. */
  4276. Size.prototype.copyFromFloats = function (width, height) {
  4277. this.width = width;
  4278. this.height = height;
  4279. return this;
  4280. };
  4281. /**
  4282. * Updates in place the current Size from the given floats.
  4283. * Returns the updated Size.
  4284. */
  4285. Size.prototype.set = function (width, height) {
  4286. return this.copyFromFloats(width, height);
  4287. };
  4288. /**
  4289. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4290. */
  4291. Size.prototype.multiplyByFloats = function (w, h) {
  4292. return new Size(this.width * w, this.height * h);
  4293. };
  4294. /**
  4295. * Returns a new Size copied from the given one.
  4296. */
  4297. Size.prototype.clone = function () {
  4298. return new Size(this.width, this.height);
  4299. };
  4300. /**
  4301. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4302. */
  4303. Size.prototype.equals = function (other) {
  4304. if (!other) {
  4305. return false;
  4306. }
  4307. return (this.width === other.width) && (this.height === other.height);
  4308. };
  4309. Object.defineProperty(Size.prototype, "surface", {
  4310. /**
  4311. * Returns the surface of the Size : width * height (float).
  4312. */
  4313. get: function () {
  4314. return this.width * this.height;
  4315. },
  4316. enumerable: true,
  4317. configurable: true
  4318. });
  4319. /**
  4320. * Returns a new Size set to (0.0, 0.0)
  4321. */
  4322. Size.Zero = function () {
  4323. return new Size(0.0, 0.0);
  4324. };
  4325. /**
  4326. * Returns a new Size set as the addition result of the current Size and the given one.
  4327. */
  4328. Size.prototype.add = function (otherSize) {
  4329. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4330. return r;
  4331. };
  4332. /**
  4333. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4334. */
  4335. Size.prototype.subtract = function (otherSize) {
  4336. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4337. return r;
  4338. };
  4339. /**
  4340. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4341. */
  4342. Size.Lerp = function (start, end, amount) {
  4343. var w = start.width + ((end.width - start.width) * amount);
  4344. var h = start.height + ((end.height - start.height) * amount);
  4345. return new Size(w, h);
  4346. };
  4347. return Size;
  4348. }());
  4349. BABYLON.Size = Size;
  4350. /**
  4351. * Class used to store quaternion data
  4352. * @see https://en.wikipedia.org/wiki/Quaternion
  4353. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4354. */
  4355. var Quaternion = /** @class */ (function () {
  4356. /**
  4357. * Creates a new Quaternion from the given floats
  4358. * @param x defines the first component (0 by default)
  4359. * @param y defines the second component (0 by default)
  4360. * @param z defines the third component (0 by default)
  4361. * @param w defines the fourth component (1.0 by default)
  4362. */
  4363. function Quaternion(
  4364. /** defines the first component (0 by default) */
  4365. x,
  4366. /** defines the second component (0 by default) */
  4367. y,
  4368. /** defines the third component (0 by default) */
  4369. z,
  4370. /** defines the fourth component (1.0 by default) */
  4371. w) {
  4372. if (x === void 0) { x = 0.0; }
  4373. if (y === void 0) { y = 0.0; }
  4374. if (z === void 0) { z = 0.0; }
  4375. if (w === void 0) { w = 1.0; }
  4376. this.x = x;
  4377. this.y = y;
  4378. this.z = z;
  4379. this.w = w;
  4380. }
  4381. /**
  4382. * Gets a string representation for the current quaternion
  4383. * @returns a string with the Quaternion coordinates
  4384. */
  4385. Quaternion.prototype.toString = function () {
  4386. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4387. };
  4388. /**
  4389. * Gets the class name of the quaternion
  4390. * @returns the string "Quaternion"
  4391. */
  4392. Quaternion.prototype.getClassName = function () {
  4393. return "Quaternion";
  4394. };
  4395. /**
  4396. * Gets a hash code for this quaternion
  4397. * @returns the quaternion hash code
  4398. */
  4399. Quaternion.prototype.getHashCode = function () {
  4400. var hash = this.x || 0;
  4401. hash = (hash * 397) ^ (this.y || 0);
  4402. hash = (hash * 397) ^ (this.z || 0);
  4403. hash = (hash * 397) ^ (this.w || 0);
  4404. return hash;
  4405. };
  4406. /**
  4407. * Copy the quaternion to an array
  4408. * @returns a new array populated with 4 elements from the quaternion coordinates
  4409. */
  4410. Quaternion.prototype.asArray = function () {
  4411. return [this.x, this.y, this.z, this.w];
  4412. };
  4413. /**
  4414. * Check if two quaternions are equals
  4415. * @param otherQuaternion defines the second operand
  4416. * @return true if the current quaternion and the given one coordinates are strictly equals
  4417. */
  4418. Quaternion.prototype.equals = function (otherQuaternion) {
  4419. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4420. };
  4421. /**
  4422. * Clone the current quaternion
  4423. * @returns a new quaternion copied from the current one
  4424. */
  4425. Quaternion.prototype.clone = function () {
  4426. return new Quaternion(this.x, this.y, this.z, this.w);
  4427. };
  4428. /**
  4429. * Copy a quaternion to the current one
  4430. * @param other defines the other quaternion
  4431. * @returns the updated current quaternion
  4432. */
  4433. Quaternion.prototype.copyFrom = function (other) {
  4434. this.x = other.x;
  4435. this.y = other.y;
  4436. this.z = other.z;
  4437. this.w = other.w;
  4438. return this;
  4439. };
  4440. /**
  4441. * Updates the current quaternion with the given float coordinates
  4442. * @param x defines the x coordinate
  4443. * @param y defines the y coordinate
  4444. * @param z defines the z coordinate
  4445. * @param w defines the w coordinate
  4446. * @returns the updated current quaternion
  4447. */
  4448. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4449. this.x = x;
  4450. this.y = y;
  4451. this.z = z;
  4452. this.w = w;
  4453. return this;
  4454. };
  4455. /**
  4456. * Updates the current quaternion from the given float coordinates
  4457. * @param x defines the x coordinate
  4458. * @param y defines the y coordinate
  4459. * @param z defines the z coordinate
  4460. * @param w defines the w coordinate
  4461. * @returns the updated current quaternion
  4462. */
  4463. Quaternion.prototype.set = function (x, y, z, w) {
  4464. return this.copyFromFloats(x, y, z, w);
  4465. };
  4466. /**
  4467. * Adds two quaternions
  4468. * @param other defines the second operand
  4469. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4470. */
  4471. Quaternion.prototype.add = function (other) {
  4472. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4473. };
  4474. /**
  4475. * Add a quaternion to the current one
  4476. * @param other defines the quaternion to add
  4477. * @returns the current quaternion
  4478. */
  4479. Quaternion.prototype.addInPlace = function (other) {
  4480. this.x += other.x;
  4481. this.y += other.y;
  4482. this.z += other.z;
  4483. this.w += other.w;
  4484. return this;
  4485. };
  4486. /**
  4487. * Subtract two quaternions
  4488. * @param other defines the second operand
  4489. * @returns a new quaternion as the subtraction result of the given one from the current one
  4490. */
  4491. Quaternion.prototype.subtract = function (other) {
  4492. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4493. };
  4494. /**
  4495. * Multiplies the current quaternion by a scale factor
  4496. * @param value defines the scale factor
  4497. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4498. */
  4499. Quaternion.prototype.scale = function (value) {
  4500. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4501. };
  4502. /**
  4503. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4504. * @param scale defines the scale factor
  4505. * @param result defines the Quaternion object where to store the result
  4506. * @returns the unmodified current quaternion
  4507. */
  4508. Quaternion.prototype.scaleToRef = function (scale, result) {
  4509. result.x = this.x * scale;
  4510. result.y = this.y * scale;
  4511. result.z = this.z * scale;
  4512. result.w = this.w * scale;
  4513. return this;
  4514. };
  4515. /**
  4516. * Multiplies in place the current quaternion by a scale factor
  4517. * @param value defines the scale factor
  4518. * @returns the current modified quaternion
  4519. */
  4520. Quaternion.prototype.scaleInPlace = function (value) {
  4521. this.x *= value;
  4522. this.y *= value;
  4523. this.z *= value;
  4524. this.w *= value;
  4525. return this;
  4526. };
  4527. /**
  4528. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4529. * @param scale defines the scale factor
  4530. * @param result defines the Quaternion object where to store the result
  4531. * @returns the unmodified current quaternion
  4532. */
  4533. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4534. result.x += this.x * scale;
  4535. result.y += this.y * scale;
  4536. result.z += this.z * scale;
  4537. result.w += this.w * scale;
  4538. return this;
  4539. };
  4540. /**
  4541. * Multiplies two quaternions
  4542. * @param q1 defines the second operand
  4543. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4544. */
  4545. Quaternion.prototype.multiply = function (q1) {
  4546. var result = new Quaternion(0, 0, 0, 1.0);
  4547. this.multiplyToRef(q1, result);
  4548. return result;
  4549. };
  4550. /**
  4551. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4552. * @param q1 defines the second operand
  4553. * @param result defines the target quaternion
  4554. * @returns the current quaternion
  4555. */
  4556. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4557. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4558. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4559. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4560. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4561. result.copyFromFloats(x, y, z, w);
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4566. * @param q1 defines the second operand
  4567. * @returns the currentupdated quaternion
  4568. */
  4569. Quaternion.prototype.multiplyInPlace = function (q1) {
  4570. this.multiplyToRef(q1, this);
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4575. * @param ref defines the target quaternion
  4576. * @returns the current quaternion
  4577. */
  4578. Quaternion.prototype.conjugateToRef = function (ref) {
  4579. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4580. return this;
  4581. };
  4582. /**
  4583. * Conjugates in place (1-q) the current quaternion
  4584. * @returns the current updated quaternion
  4585. */
  4586. Quaternion.prototype.conjugateInPlace = function () {
  4587. this.x *= -1;
  4588. this.y *= -1;
  4589. this.z *= -1;
  4590. return this;
  4591. };
  4592. /**
  4593. * Conjugates in place (1-q) the current quaternion
  4594. * @returns a new quaternion
  4595. */
  4596. Quaternion.prototype.conjugate = function () {
  4597. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4598. return result;
  4599. };
  4600. /**
  4601. * Gets length of current quaternion
  4602. * @returns the quaternion length (float)
  4603. */
  4604. Quaternion.prototype.length = function () {
  4605. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4606. };
  4607. /**
  4608. * Normalize in place the current quaternion
  4609. * @returns the current updated quaternion
  4610. */
  4611. Quaternion.prototype.normalize = function () {
  4612. var length = 1.0 / this.length();
  4613. this.x *= length;
  4614. this.y *= length;
  4615. this.z *= length;
  4616. this.w *= length;
  4617. return this;
  4618. };
  4619. /**
  4620. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4621. * @param order is a reserved parameter and is ignore for now
  4622. * @returns a new Vector3 containing the Euler angles
  4623. */
  4624. Quaternion.prototype.toEulerAngles = function (order) {
  4625. if (order === void 0) { order = "YZX"; }
  4626. var result = Vector3.Zero();
  4627. this.toEulerAnglesToRef(result, order);
  4628. return result;
  4629. };
  4630. /**
  4631. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4632. * @param result defines the vector which will be filled with the Euler angles
  4633. * @param order is a reserved parameter and is ignore for now
  4634. * @returns the current unchanged quaternion
  4635. */
  4636. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4637. if (order === void 0) { order = "YZX"; }
  4638. var qz = this.z;
  4639. var qx = this.x;
  4640. var qy = this.y;
  4641. var qw = this.w;
  4642. var sqw = qw * qw;
  4643. var sqz = qz * qz;
  4644. var sqx = qx * qx;
  4645. var sqy = qy * qy;
  4646. var zAxisY = qy * qz - qx * qw;
  4647. var limit = .4999999;
  4648. if (zAxisY < -limit) {
  4649. result.y = 2 * Math.atan2(qy, qw);
  4650. result.x = Math.PI / 2;
  4651. result.z = 0;
  4652. }
  4653. else if (zAxisY > limit) {
  4654. result.y = 2 * Math.atan2(qy, qw);
  4655. result.x = -Math.PI / 2;
  4656. result.z = 0;
  4657. }
  4658. else {
  4659. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4660. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4661. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4662. }
  4663. return this;
  4664. };
  4665. /**
  4666. * Updates the given rotation matrix with the current quaternion values
  4667. * @param result defines the target matrix
  4668. * @returns the current unchanged quaternion
  4669. */
  4670. Quaternion.prototype.toRotationMatrix = function (result) {
  4671. var xx = this.x * this.x;
  4672. var yy = this.y * this.y;
  4673. var zz = this.z * this.z;
  4674. var xy = this.x * this.y;
  4675. var zw = this.z * this.w;
  4676. var zx = this.z * this.x;
  4677. var yw = this.y * this.w;
  4678. var yz = this.y * this.z;
  4679. var xw = this.x * this.w;
  4680. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4681. result.m[1] = 2.0 * (xy + zw);
  4682. result.m[2] = 2.0 * (zx - yw);
  4683. result.m[3] = 0;
  4684. result.m[4] = 2.0 * (xy - zw);
  4685. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4686. result.m[6] = 2.0 * (yz + xw);
  4687. result.m[7] = 0;
  4688. result.m[8] = 2.0 * (zx + yw);
  4689. result.m[9] = 2.0 * (yz - xw);
  4690. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4691. result.m[11] = 0;
  4692. result.m[12] = 0;
  4693. result.m[13] = 0;
  4694. result.m[14] = 0;
  4695. result.m[15] = 1.0;
  4696. result._markAsUpdated();
  4697. return this;
  4698. };
  4699. /**
  4700. * Updates the current quaternion from the given rotation matrix values
  4701. * @param matrix defines the source matrix
  4702. * @returns the current updated quaternion
  4703. */
  4704. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4705. Quaternion.FromRotationMatrixToRef(matrix, this);
  4706. return this;
  4707. };
  4708. // Statics
  4709. /**
  4710. * Creates a new quaternion from a rotation matrix
  4711. * @param matrix defines the source matrix
  4712. * @returns a new quaternion created from the given rotation matrix values
  4713. */
  4714. Quaternion.FromRotationMatrix = function (matrix) {
  4715. var result = new Quaternion();
  4716. Quaternion.FromRotationMatrixToRef(matrix, result);
  4717. return result;
  4718. };
  4719. /**
  4720. * Updates the given quaternion with the given rotation matrix values
  4721. * @param matrix defines the source matrix
  4722. * @param result defines the target quaternion
  4723. */
  4724. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4725. var data = matrix.m;
  4726. var m11 = data[0], m12 = data[4], m13 = data[8];
  4727. var m21 = data[1], m22 = data[5], m23 = data[9];
  4728. var m31 = data[2], m32 = data[6], m33 = data[10];
  4729. var trace = m11 + m22 + m33;
  4730. var s;
  4731. if (trace > 0) {
  4732. s = 0.5 / Math.sqrt(trace + 1.0);
  4733. result.w = 0.25 / s;
  4734. result.x = (m32 - m23) * s;
  4735. result.y = (m13 - m31) * s;
  4736. result.z = (m21 - m12) * s;
  4737. }
  4738. else if (m11 > m22 && m11 > m33) {
  4739. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4740. result.w = (m32 - m23) / s;
  4741. result.x = 0.25 * s;
  4742. result.y = (m12 + m21) / s;
  4743. result.z = (m13 + m31) / s;
  4744. }
  4745. else if (m22 > m33) {
  4746. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4747. result.w = (m13 - m31) / s;
  4748. result.x = (m12 + m21) / s;
  4749. result.y = 0.25 * s;
  4750. result.z = (m23 + m32) / s;
  4751. }
  4752. else {
  4753. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4754. result.w = (m21 - m12) / s;
  4755. result.x = (m13 + m31) / s;
  4756. result.y = (m23 + m32) / s;
  4757. result.z = 0.25 * s;
  4758. }
  4759. };
  4760. /**
  4761. * Returns the dot product (float) between the quaternions "left" and "right"
  4762. * @param left defines the left operand
  4763. * @param right defines the right operand
  4764. * @returns the dot product
  4765. */
  4766. Quaternion.Dot = function (left, right) {
  4767. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4768. };
  4769. /**
  4770. * Checks if the two quaternions are close to each other
  4771. * @param quat0 defines the first quaternion to check
  4772. * @param quat1 defines the second quaternion to check
  4773. * @returns true if the two quaternions are close to each other
  4774. */
  4775. Quaternion.AreClose = function (quat0, quat1) {
  4776. var dot = Quaternion.Dot(quat0, quat1);
  4777. return dot >= 0;
  4778. };
  4779. /**
  4780. * Creates an empty quaternion
  4781. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4782. */
  4783. Quaternion.Zero = function () {
  4784. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4785. };
  4786. /**
  4787. * Inverse a given quaternion
  4788. * @param q defines the source quaternion
  4789. * @returns a new quaternion as the inverted current quaternion
  4790. */
  4791. Quaternion.Inverse = function (q) {
  4792. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4793. };
  4794. /**
  4795. * Creates an identity quaternion
  4796. * @returns the identity quaternion
  4797. */
  4798. Quaternion.Identity = function () {
  4799. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4800. };
  4801. /**
  4802. * Gets a boolean indicating if the given quaternion is identity
  4803. * @param quaternion defines the quaternion to check
  4804. * @returns true if the quaternion is identity
  4805. */
  4806. Quaternion.IsIdentity = function (quaternion) {
  4807. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4808. };
  4809. /**
  4810. * Creates a quaternion from a rotation around an axis
  4811. * @param axis defines the axis to use
  4812. * @param angle defines the angle to use
  4813. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4814. */
  4815. Quaternion.RotationAxis = function (axis, angle) {
  4816. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4817. };
  4818. /**
  4819. * Creates a rotation around an axis and stores it into the given quaternion
  4820. * @param axis defines the axis to use
  4821. * @param angle defines the angle to use
  4822. * @param result defines the target quaternion
  4823. * @returns the target quaternion
  4824. */
  4825. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4826. var sin = Math.sin(angle / 2);
  4827. axis.normalize();
  4828. result.w = Math.cos(angle / 2);
  4829. result.x = axis.x * sin;
  4830. result.y = axis.y * sin;
  4831. result.z = axis.z * sin;
  4832. return result;
  4833. };
  4834. /**
  4835. * Creates a new quaternion from data stored into an array
  4836. * @param array defines the data source
  4837. * @param offset defines the offset in the source array where the data starts
  4838. * @returns a new quaternion
  4839. */
  4840. Quaternion.FromArray = function (array, offset) {
  4841. if (!offset) {
  4842. offset = 0;
  4843. }
  4844. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4845. };
  4846. /**
  4847. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4848. * @param yaw defines the rotation around Y axis
  4849. * @param pitch defines the rotation around X axis
  4850. * @param roll defines the rotation around Z axis
  4851. * @returns the new quaternion
  4852. */
  4853. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4854. var q = new Quaternion();
  4855. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4856. return q;
  4857. };
  4858. /**
  4859. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4860. * @param yaw defines the rotation around Y axis
  4861. * @param pitch defines the rotation around X axis
  4862. * @param roll defines the rotation around Z axis
  4863. * @param result defines the target quaternion
  4864. */
  4865. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4866. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4867. var halfRoll = roll * 0.5;
  4868. var halfPitch = pitch * 0.5;
  4869. var halfYaw = yaw * 0.5;
  4870. var sinRoll = Math.sin(halfRoll);
  4871. var cosRoll = Math.cos(halfRoll);
  4872. var sinPitch = Math.sin(halfPitch);
  4873. var cosPitch = Math.cos(halfPitch);
  4874. var sinYaw = Math.sin(halfYaw);
  4875. var cosYaw = Math.cos(halfYaw);
  4876. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4877. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4878. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4879. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4880. };
  4881. /**
  4882. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4883. * @param alpha defines the rotation around first axis
  4884. * @param beta defines the rotation around second axis
  4885. * @param gamma defines the rotation around third axis
  4886. * @returns the new quaternion
  4887. */
  4888. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4889. var result = new Quaternion();
  4890. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4891. return result;
  4892. };
  4893. /**
  4894. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4895. * @param alpha defines the rotation around first axis
  4896. * @param beta defines the rotation around second axis
  4897. * @param gamma defines the rotation around third axis
  4898. * @param result defines the target quaternion
  4899. */
  4900. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4901. // Produces a quaternion from Euler angles in the z-x-z orientation
  4902. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4903. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4904. var halfBeta = beta * 0.5;
  4905. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4906. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4907. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4908. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4909. };
  4910. /**
  4911. * 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)
  4912. * @param axis1 defines the first axis
  4913. * @param axis2 defines the second axis
  4914. * @param axis3 defines the third axis
  4915. * @returns the new quaternion
  4916. */
  4917. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4918. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4919. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4920. return quat;
  4921. };
  4922. /**
  4923. * 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
  4924. * @param axis1 defines the first axis
  4925. * @param axis2 defines the second axis
  4926. * @param axis3 defines the third axis
  4927. * @param ref defines the target quaternion
  4928. */
  4929. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4930. var rotMat = MathTmp.Matrix[0];
  4931. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4932. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4933. };
  4934. /**
  4935. * Interpolates between two quaternions
  4936. * @param left defines first quaternion
  4937. * @param right defines second quaternion
  4938. * @param amount defines the gradient to use
  4939. * @returns the new interpolated quaternion
  4940. */
  4941. Quaternion.Slerp = function (left, right, amount) {
  4942. var result = Quaternion.Identity();
  4943. Quaternion.SlerpToRef(left, right, amount, result);
  4944. return result;
  4945. };
  4946. /**
  4947. * Interpolates between two quaternions and stores it into a target quaternion
  4948. * @param left defines first quaternion
  4949. * @param right defines second quaternion
  4950. * @param amount defines the gradient to use
  4951. * @param result defines the target quaternion
  4952. */
  4953. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4954. var num2;
  4955. var num3;
  4956. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4957. var flag = false;
  4958. if (num4 < 0) {
  4959. flag = true;
  4960. num4 = -num4;
  4961. }
  4962. if (num4 > 0.999999) {
  4963. num3 = 1 - amount;
  4964. num2 = flag ? -amount : amount;
  4965. }
  4966. else {
  4967. var num5 = Math.acos(num4);
  4968. var num6 = (1.0 / Math.sin(num5));
  4969. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4970. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4971. }
  4972. result.x = (num3 * left.x) + (num2 * right.x);
  4973. result.y = (num3 * left.y) + (num2 * right.y);
  4974. result.z = (num3 * left.z) + (num2 * right.z);
  4975. result.w = (num3 * left.w) + (num2 * right.w);
  4976. };
  4977. /**
  4978. * Interpolate between two quaternions using Hermite interpolation
  4979. * @param value1 defines first quaternion
  4980. * @param tangent1 defines the incoming tangent
  4981. * @param value2 defines second quaternion
  4982. * @param tangent2 defines the outgoing tangent
  4983. * @param amount defines the target quaternion
  4984. * @returns the new interpolated quaternion
  4985. */
  4986. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4987. var squared = amount * amount;
  4988. var cubed = amount * squared;
  4989. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4990. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4991. var part3 = (cubed - (2.0 * squared)) + amount;
  4992. var part4 = cubed - squared;
  4993. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4994. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4995. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4996. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4997. return new Quaternion(x, y, z, w);
  4998. };
  4999. return Quaternion;
  5000. }());
  5001. BABYLON.Quaternion = Quaternion;
  5002. /**
  5003. * Class used to store matrix data (4x4)
  5004. */
  5005. var Matrix = /** @class */ (function () {
  5006. /**
  5007. * Creates an empty matrix (filled with zeros)
  5008. */
  5009. function Matrix() {
  5010. this._isIdentity = false;
  5011. this._isIdentityDirty = true;
  5012. /**
  5013. * Gets or sets the internal data of the matrix
  5014. */
  5015. this.m = new Float32Array(16);
  5016. this._markAsUpdated();
  5017. }
  5018. /** @hidden */
  5019. Matrix.prototype._markAsUpdated = function () {
  5020. this.updateFlag = Matrix._updateFlagSeed++;
  5021. this._isIdentityDirty = true;
  5022. };
  5023. // Properties
  5024. /**
  5025. * Check if the current matrix is indentity
  5026. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5027. * @returns true is the matrix is the identity matrix
  5028. */
  5029. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5030. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5031. if (this._isIdentityDirty) {
  5032. this._isIdentityDirty = false;
  5033. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5034. this._isIdentity = false;
  5035. }
  5036. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5037. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5038. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5039. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5040. this._isIdentity = false;
  5041. }
  5042. else {
  5043. this._isIdentity = true;
  5044. }
  5045. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5046. this._isIdentity = false;
  5047. }
  5048. }
  5049. return this._isIdentity;
  5050. };
  5051. /**
  5052. * Gets the determinant of the matrix
  5053. * @returns the matrix determinant
  5054. */
  5055. Matrix.prototype.determinant = function () {
  5056. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5057. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5058. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5059. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5060. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5061. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5062. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5063. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5064. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5065. };
  5066. // Methods
  5067. /**
  5068. * Returns the matrix as a Float32Array
  5069. * @returns the matrix underlying array
  5070. */
  5071. Matrix.prototype.toArray = function () {
  5072. return this.m;
  5073. };
  5074. /**
  5075. * Returns the matrix as a Float32Array
  5076. * @returns the matrix underlying array.
  5077. */
  5078. Matrix.prototype.asArray = function () {
  5079. return this.toArray();
  5080. };
  5081. /**
  5082. * Inverts the current matrix in place
  5083. * @returns the current inverted matrix
  5084. */
  5085. Matrix.prototype.invert = function () {
  5086. this.invertToRef(this);
  5087. return this;
  5088. };
  5089. /**
  5090. * Sets all the matrix elements to zero
  5091. * @returns the current matrix
  5092. */
  5093. Matrix.prototype.reset = function () {
  5094. for (var index = 0; index < 16; index++) {
  5095. this.m[index] = 0.0;
  5096. }
  5097. this._markAsUpdated();
  5098. return this;
  5099. };
  5100. /**
  5101. * Adds the current matrix with a second one
  5102. * @param other defines the matrix to add
  5103. * @returns a new matrix as the addition of the current matrix and the given one
  5104. */
  5105. Matrix.prototype.add = function (other) {
  5106. var result = new Matrix();
  5107. this.addToRef(other, result);
  5108. return result;
  5109. };
  5110. /**
  5111. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5112. * @param other defines the matrix to add
  5113. * @param result defines the target matrix
  5114. * @returns the current matrix
  5115. */
  5116. Matrix.prototype.addToRef = function (other, result) {
  5117. for (var index = 0; index < 16; index++) {
  5118. result.m[index] = this.m[index] + other.m[index];
  5119. }
  5120. result._markAsUpdated();
  5121. return this;
  5122. };
  5123. /**
  5124. * Adds in place the given matrix to the current matrix
  5125. * @param other defines the second operand
  5126. * @returns the current updated matrix
  5127. */
  5128. Matrix.prototype.addToSelf = function (other) {
  5129. for (var index = 0; index < 16; index++) {
  5130. this.m[index] += other.m[index];
  5131. }
  5132. this._markAsUpdated();
  5133. return this;
  5134. };
  5135. /**
  5136. * Sets the given matrix to the current inverted Matrix
  5137. * @param other defines the target matrix
  5138. * @returns the unmodified current matrix
  5139. */
  5140. Matrix.prototype.invertToRef = function (other) {
  5141. var l1 = this.m[0];
  5142. var l2 = this.m[1];
  5143. var l3 = this.m[2];
  5144. var l4 = this.m[3];
  5145. var l5 = this.m[4];
  5146. var l6 = this.m[5];
  5147. var l7 = this.m[6];
  5148. var l8 = this.m[7];
  5149. var l9 = this.m[8];
  5150. var l10 = this.m[9];
  5151. var l11 = this.m[10];
  5152. var l12 = this.m[11];
  5153. var l13 = this.m[12];
  5154. var l14 = this.m[13];
  5155. var l15 = this.m[14];
  5156. var l16 = this.m[15];
  5157. var l17 = (l11 * l16) - (l12 * l15);
  5158. var l18 = (l10 * l16) - (l12 * l14);
  5159. var l19 = (l10 * l15) - (l11 * l14);
  5160. var l20 = (l9 * l16) - (l12 * l13);
  5161. var l21 = (l9 * l15) - (l11 * l13);
  5162. var l22 = (l9 * l14) - (l10 * l13);
  5163. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5164. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5165. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5166. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5167. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5168. var l28 = (l7 * l16) - (l8 * l15);
  5169. var l29 = (l6 * l16) - (l8 * l14);
  5170. var l30 = (l6 * l15) - (l7 * l14);
  5171. var l31 = (l5 * l16) - (l8 * l13);
  5172. var l32 = (l5 * l15) - (l7 * l13);
  5173. var l33 = (l5 * l14) - (l6 * l13);
  5174. var l34 = (l7 * l12) - (l8 * l11);
  5175. var l35 = (l6 * l12) - (l8 * l10);
  5176. var l36 = (l6 * l11) - (l7 * l10);
  5177. var l37 = (l5 * l12) - (l8 * l9);
  5178. var l38 = (l5 * l11) - (l7 * l9);
  5179. var l39 = (l5 * l10) - (l6 * l9);
  5180. other.m[0] = l23 * l27;
  5181. other.m[4] = l24 * l27;
  5182. other.m[8] = l25 * l27;
  5183. other.m[12] = l26 * l27;
  5184. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5185. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5186. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5187. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5188. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5189. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5190. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5191. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5192. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5193. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5194. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5195. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5196. other._markAsUpdated();
  5197. return this;
  5198. };
  5199. /**
  5200. * Inserts the translation vector (using 3 floats) in the current matrix
  5201. * @param x defines the 1st component of the translation
  5202. * @param y defines the 2nd component of the translation
  5203. * @param z defines the 3rd component of the translation
  5204. * @returns the current updated matrix
  5205. */
  5206. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5207. this.m[12] = x;
  5208. this.m[13] = y;
  5209. this.m[14] = z;
  5210. this._markAsUpdated();
  5211. return this;
  5212. };
  5213. /**
  5214. * Inserts the translation vector in the current matrix
  5215. * @param vector3 defines the translation to insert
  5216. * @returns the current updated matrix
  5217. */
  5218. Matrix.prototype.setTranslation = function (vector3) {
  5219. this.m[12] = vector3.x;
  5220. this.m[13] = vector3.y;
  5221. this.m[14] = vector3.z;
  5222. this._markAsUpdated();
  5223. return this;
  5224. };
  5225. /**
  5226. * Gets the translation value of the current matrix
  5227. * @returns a new Vector3 as the extracted translation from the matrix
  5228. */
  5229. Matrix.prototype.getTranslation = function () {
  5230. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5231. };
  5232. /**
  5233. * Fill a Vector3 with the extracted translation from the matrix
  5234. * @param result defines the Vector3 where to store the translation
  5235. * @returns the current matrix
  5236. */
  5237. Matrix.prototype.getTranslationToRef = function (result) {
  5238. result.x = this.m[12];
  5239. result.y = this.m[13];
  5240. result.z = this.m[14];
  5241. return this;
  5242. };
  5243. /**
  5244. * Remove rotation and scaling part from the matrix
  5245. * @returns the updated matrix
  5246. */
  5247. Matrix.prototype.removeRotationAndScaling = function () {
  5248. this.setRowFromFloats(0, 1, 0, 0, 0);
  5249. this.setRowFromFloats(1, 0, 1, 0, 0);
  5250. this.setRowFromFloats(2, 0, 0, 1, 0);
  5251. return this;
  5252. };
  5253. /**
  5254. * Multiply two matrices
  5255. * @param other defines the second operand
  5256. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5257. */
  5258. Matrix.prototype.multiply = function (other) {
  5259. var result = new Matrix();
  5260. this.multiplyToRef(other, result);
  5261. return result;
  5262. };
  5263. /**
  5264. * Copy the current matrix from the given one
  5265. * @param other defines the source matrix
  5266. * @returns the current updated matrix
  5267. */
  5268. Matrix.prototype.copyFrom = function (other) {
  5269. for (var index = 0; index < 16; index++) {
  5270. this.m[index] = other.m[index];
  5271. }
  5272. this._markAsUpdated();
  5273. return this;
  5274. };
  5275. /**
  5276. * Populates the given array from the starting index with the current matrix values
  5277. * @param array defines the target array
  5278. * @param offset defines the offset in the target array where to start storing values
  5279. * @returns the current matrix
  5280. */
  5281. Matrix.prototype.copyToArray = function (array, offset) {
  5282. if (offset === void 0) { offset = 0; }
  5283. for (var index = 0; index < 16; index++) {
  5284. array[offset + index] = this.m[index];
  5285. }
  5286. return this;
  5287. };
  5288. /**
  5289. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5290. * @param other defines the second operand
  5291. * @param result defines the matrix where to store the multiplication
  5292. * @returns the current matrix
  5293. */
  5294. Matrix.prototype.multiplyToRef = function (other, result) {
  5295. this.multiplyToArray(other, result.m, 0);
  5296. result._markAsUpdated();
  5297. return this;
  5298. };
  5299. /**
  5300. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5301. * @param other defines the second operand
  5302. * @param result defines the array where to store the multiplication
  5303. * @param offset defines the offset in the target array where to start storing values
  5304. * @returns the current matrix
  5305. */
  5306. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5307. var tm0 = this.m[0];
  5308. var tm1 = this.m[1];
  5309. var tm2 = this.m[2];
  5310. var tm3 = this.m[3];
  5311. var tm4 = this.m[4];
  5312. var tm5 = this.m[5];
  5313. var tm6 = this.m[6];
  5314. var tm7 = this.m[7];
  5315. var tm8 = this.m[8];
  5316. var tm9 = this.m[9];
  5317. var tm10 = this.m[10];
  5318. var tm11 = this.m[11];
  5319. var tm12 = this.m[12];
  5320. var tm13 = this.m[13];
  5321. var tm14 = this.m[14];
  5322. var tm15 = this.m[15];
  5323. var om0 = other.m[0];
  5324. var om1 = other.m[1];
  5325. var om2 = other.m[2];
  5326. var om3 = other.m[3];
  5327. var om4 = other.m[4];
  5328. var om5 = other.m[5];
  5329. var om6 = other.m[6];
  5330. var om7 = other.m[7];
  5331. var om8 = other.m[8];
  5332. var om9 = other.m[9];
  5333. var om10 = other.m[10];
  5334. var om11 = other.m[11];
  5335. var om12 = other.m[12];
  5336. var om13 = other.m[13];
  5337. var om14 = other.m[14];
  5338. var om15 = other.m[15];
  5339. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5340. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5341. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5342. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5343. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5344. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5345. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5346. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5347. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5348. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5349. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5350. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5351. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5352. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5353. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5354. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5355. return this;
  5356. };
  5357. /**
  5358. * Check equality between this matrix and a second one
  5359. * @param value defines the second matrix to compare
  5360. * @returns true is the current matrix and the given one values are strictly equal
  5361. */
  5362. Matrix.prototype.equals = function (value) {
  5363. return value &&
  5364. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5365. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5366. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5367. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5368. };
  5369. /**
  5370. * Clone the current matrix
  5371. * @returns a new matrix from the current matrix
  5372. */
  5373. Matrix.prototype.clone = function () {
  5374. 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]);
  5375. };
  5376. /**
  5377. * Returns the name of the current matrix class
  5378. * @returns the string "Matrix"
  5379. */
  5380. Matrix.prototype.getClassName = function () {
  5381. return "Matrix";
  5382. };
  5383. /**
  5384. * Gets the hash code of the current matrix
  5385. * @returns the hash code
  5386. */
  5387. Matrix.prototype.getHashCode = function () {
  5388. var hash = this.m[0] || 0;
  5389. for (var i = 1; i < 16; i++) {
  5390. hash = (hash * 397) ^ (this.m[i] || 0);
  5391. }
  5392. return hash;
  5393. };
  5394. /**
  5395. * Decomposes the current Matrix into a translation, rotation and scaling components
  5396. * @param scale defines the scale vector3 given as a reference to update
  5397. * @param rotation defines the rotation quaternion given as a reference to update
  5398. * @param translation defines the translation vector3 given as a reference to update
  5399. * @returns true if operation was successful
  5400. */
  5401. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5402. if (translation) {
  5403. translation.x = this.m[12];
  5404. translation.y = this.m[13];
  5405. translation.z = this.m[14];
  5406. }
  5407. scale = scale || MathTmp.Vector3[0];
  5408. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5409. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5410. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5411. if (this.determinant() <= 0) {
  5412. scale.y *= -1;
  5413. }
  5414. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5415. if (rotation) {
  5416. rotation.x = 0;
  5417. rotation.y = 0;
  5418. rotation.z = 0;
  5419. rotation.w = 1;
  5420. }
  5421. return false;
  5422. }
  5423. if (rotation) {
  5424. 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]);
  5425. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5426. }
  5427. return true;
  5428. };
  5429. /**
  5430. * Gets specific row of the matrix
  5431. * @param index defines the number of the row to get
  5432. * @returns the index-th row of the current matrix as a new Vector4
  5433. */
  5434. Matrix.prototype.getRow = function (index) {
  5435. if (index < 0 || index > 3) {
  5436. return null;
  5437. }
  5438. var i = index * 4;
  5439. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5440. };
  5441. /**
  5442. * Sets the index-th row of the current matrix to the vector4 values
  5443. * @param index defines the number of the row to set
  5444. * @param row defines the target vector4
  5445. * @returns the updated current matrix
  5446. */
  5447. Matrix.prototype.setRow = function (index, row) {
  5448. if (index < 0 || index > 3) {
  5449. return this;
  5450. }
  5451. var i = index * 4;
  5452. this.m[i + 0] = row.x;
  5453. this.m[i + 1] = row.y;
  5454. this.m[i + 2] = row.z;
  5455. this.m[i + 3] = row.w;
  5456. this._markAsUpdated();
  5457. return this;
  5458. };
  5459. /**
  5460. * Compute the transpose of the matrix
  5461. * @returns the new transposed matrix
  5462. */
  5463. Matrix.prototype.transpose = function () {
  5464. return Matrix.Transpose(this);
  5465. };
  5466. /**
  5467. * Compute the transpose of the matrix and store it in a given matrix
  5468. * @param result defines the target matrix
  5469. * @returns the current matrix
  5470. */
  5471. Matrix.prototype.transposeToRef = function (result) {
  5472. Matrix.TransposeToRef(this, result);
  5473. return this;
  5474. };
  5475. /**
  5476. * Sets the index-th row of the current matrix with the given 4 x float values
  5477. * @param index defines the row index
  5478. * @param x defines the x component to set
  5479. * @param y defines the y component to set
  5480. * @param z defines the z component to set
  5481. * @param w defines the w component to set
  5482. * @returns the updated current matrix
  5483. */
  5484. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5485. if (index < 0 || index > 3) {
  5486. return this;
  5487. }
  5488. var i = index * 4;
  5489. this.m[i + 0] = x;
  5490. this.m[i + 1] = y;
  5491. this.m[i + 2] = z;
  5492. this.m[i + 3] = w;
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5498. * @param scale defines the scale factor
  5499. * @returns a new matrix
  5500. */
  5501. Matrix.prototype.scale = function (scale) {
  5502. var result = new Matrix();
  5503. this.scaleToRef(scale, result);
  5504. return result;
  5505. };
  5506. /**
  5507. * Scale the current matrix values by a factor to a given result matrix
  5508. * @param scale defines the scale factor
  5509. * @param result defines the matrix to store the result
  5510. * @returns the current matrix
  5511. */
  5512. Matrix.prototype.scaleToRef = function (scale, result) {
  5513. for (var index = 0; index < 16; index++) {
  5514. result.m[index] = this.m[index] * scale;
  5515. }
  5516. result._markAsUpdated();
  5517. return this;
  5518. };
  5519. /**
  5520. * Scale the current matrix values by a factor and add the result to a given matrix
  5521. * @param scale defines the scale factor
  5522. * @param result defines the Matrix to store the result
  5523. * @returns the current matrix
  5524. */
  5525. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5526. for (var index = 0; index < 16; index++) {
  5527. result.m[index] += this.m[index] * scale;
  5528. }
  5529. result._markAsUpdated();
  5530. return this;
  5531. };
  5532. /**
  5533. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5534. * @param ref matrix to store the result
  5535. */
  5536. Matrix.prototype.toNormalMatrix = function (ref) {
  5537. this.invertToRef(ref);
  5538. ref.transpose();
  5539. var m = ref.m;
  5540. 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);
  5541. };
  5542. /**
  5543. * Gets only rotation part of the current matrix
  5544. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5545. */
  5546. Matrix.prototype.getRotationMatrix = function () {
  5547. var result = Matrix.Identity();
  5548. this.getRotationMatrixToRef(result);
  5549. return result;
  5550. };
  5551. /**
  5552. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5553. * @param result defines the target matrix to store data to
  5554. * @returns the current matrix
  5555. */
  5556. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5557. var m = this.m;
  5558. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5559. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5560. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5561. if (this.determinant() <= 0) {
  5562. sy *= -1;
  5563. }
  5564. if (sx === 0 || sy === 0 || sz === 0) {
  5565. Matrix.IdentityToRef(result);
  5566. }
  5567. else {
  5568. 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);
  5569. }
  5570. return this;
  5571. };
  5572. // Statics
  5573. /**
  5574. * Creates a matrix from an array
  5575. * @param array defines the source array
  5576. * @param offset defines an offset in the source array
  5577. * @returns a new Matrix set from the starting index of the given array
  5578. */
  5579. Matrix.FromArray = function (array, offset) {
  5580. var result = new Matrix();
  5581. if (!offset) {
  5582. offset = 0;
  5583. }
  5584. Matrix.FromArrayToRef(array, offset, result);
  5585. return result;
  5586. };
  5587. /**
  5588. * Copy the content of an array into a given matrix
  5589. * @param array defines the source array
  5590. * @param offset defines an offset in the source array
  5591. * @param result defines the target matrix
  5592. */
  5593. Matrix.FromArrayToRef = function (array, offset, result) {
  5594. for (var index = 0; index < 16; index++) {
  5595. result.m[index] = array[index + offset];
  5596. }
  5597. result._markAsUpdated();
  5598. };
  5599. /**
  5600. * Stores an array into a matrix after having multiplied each component by a given factor
  5601. * @param array defines the source array
  5602. * @param offset defines the offset in the source array
  5603. * @param scale defines the scaling factor
  5604. * @param result defines the target matrix
  5605. */
  5606. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5607. for (var index = 0; index < 16; index++) {
  5608. result.m[index] = array[index + offset] * scale;
  5609. }
  5610. result._markAsUpdated();
  5611. };
  5612. /**
  5613. * Stores a list of values (16) inside a given matrix
  5614. * @param initialM11 defines 1st value of 1st row
  5615. * @param initialM12 defines 2nd value of 1st row
  5616. * @param initialM13 defines 3rd value of 1st row
  5617. * @param initialM14 defines 4th value of 1st row
  5618. * @param initialM21 defines 1st value of 2nd row
  5619. * @param initialM22 defines 2nd value of 2nd row
  5620. * @param initialM23 defines 3rd value of 2nd row
  5621. * @param initialM24 defines 4th value of 2nd row
  5622. * @param initialM31 defines 1st value of 3rd row
  5623. * @param initialM32 defines 2nd value of 3rd row
  5624. * @param initialM33 defines 3rd value of 3rd row
  5625. * @param initialM34 defines 4th value of 3rd row
  5626. * @param initialM41 defines 1st value of 4th row
  5627. * @param initialM42 defines 2nd value of 4th row
  5628. * @param initialM43 defines 3rd value of 4th row
  5629. * @param initialM44 defines 4th value of 4th row
  5630. * @param result defines the target matrix
  5631. */
  5632. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5633. result.m[0] = initialM11;
  5634. result.m[1] = initialM12;
  5635. result.m[2] = initialM13;
  5636. result.m[3] = initialM14;
  5637. result.m[4] = initialM21;
  5638. result.m[5] = initialM22;
  5639. result.m[6] = initialM23;
  5640. result.m[7] = initialM24;
  5641. result.m[8] = initialM31;
  5642. result.m[9] = initialM32;
  5643. result.m[10] = initialM33;
  5644. result.m[11] = initialM34;
  5645. result.m[12] = initialM41;
  5646. result.m[13] = initialM42;
  5647. result.m[14] = initialM43;
  5648. result.m[15] = initialM44;
  5649. result._markAsUpdated();
  5650. };
  5651. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5652. /**
  5653. * Gets an identity matrix that must not be updated
  5654. */
  5655. get: function () {
  5656. return Matrix._identityReadOnly;
  5657. },
  5658. enumerable: true,
  5659. configurable: true
  5660. });
  5661. /**
  5662. * Creates new matrix from a list of values (16)
  5663. * @param initialM11 defines 1st value of 1st row
  5664. * @param initialM12 defines 2nd value of 1st row
  5665. * @param initialM13 defines 3rd value of 1st row
  5666. * @param initialM14 defines 4th value of 1st row
  5667. * @param initialM21 defines 1st value of 2nd row
  5668. * @param initialM22 defines 2nd value of 2nd row
  5669. * @param initialM23 defines 3rd value of 2nd row
  5670. * @param initialM24 defines 4th value of 2nd row
  5671. * @param initialM31 defines 1st value of 3rd row
  5672. * @param initialM32 defines 2nd value of 3rd row
  5673. * @param initialM33 defines 3rd value of 3rd row
  5674. * @param initialM34 defines 4th value of 3rd row
  5675. * @param initialM41 defines 1st value of 4th row
  5676. * @param initialM42 defines 2nd value of 4th row
  5677. * @param initialM43 defines 3rd value of 4th row
  5678. * @param initialM44 defines 4th value of 4th row
  5679. * @returns the new matrix
  5680. */
  5681. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5682. var result = new Matrix();
  5683. result.m[0] = initialM11;
  5684. result.m[1] = initialM12;
  5685. result.m[2] = initialM13;
  5686. result.m[3] = initialM14;
  5687. result.m[4] = initialM21;
  5688. result.m[5] = initialM22;
  5689. result.m[6] = initialM23;
  5690. result.m[7] = initialM24;
  5691. result.m[8] = initialM31;
  5692. result.m[9] = initialM32;
  5693. result.m[10] = initialM33;
  5694. result.m[11] = initialM34;
  5695. result.m[12] = initialM41;
  5696. result.m[13] = initialM42;
  5697. result.m[14] = initialM43;
  5698. result.m[15] = initialM44;
  5699. return result;
  5700. };
  5701. /**
  5702. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5703. * @param scale defines the scale vector3
  5704. * @param rotation defines the rotation quaternion
  5705. * @param translation defines the translation vector3
  5706. * @returns a new matrix
  5707. */
  5708. Matrix.Compose = function (scale, rotation, translation) {
  5709. var result = Matrix.Identity();
  5710. Matrix.ComposeToRef(scale, rotation, translation, result);
  5711. return result;
  5712. };
  5713. /**
  5714. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5715. * @param scale defines the scale vector3
  5716. * @param rotation defines the rotation quaternion
  5717. * @param translation defines the translation vector3
  5718. * @param result defines the target matrix
  5719. */
  5720. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5721. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5722. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5723. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5724. result.setTranslation(translation);
  5725. };
  5726. /**
  5727. * Creates a new identity matrix
  5728. * @returns a new identity matrix
  5729. */
  5730. Matrix.Identity = function () {
  5731. 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);
  5732. };
  5733. /**
  5734. * Creates a new identity matrix and stores the result in a given matrix
  5735. * @param result defines the target matrix
  5736. */
  5737. Matrix.IdentityToRef = function (result) {
  5738. 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);
  5739. };
  5740. /**
  5741. * Creates a new zero matrix
  5742. * @returns a new zero matrix
  5743. */
  5744. Matrix.Zero = function () {
  5745. 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);
  5746. };
  5747. /**
  5748. * Creates a new rotation matrix for "angle" radians around the X axis
  5749. * @param angle defines the angle (in radians) to use
  5750. * @return the new matrix
  5751. */
  5752. Matrix.RotationX = function (angle) {
  5753. var result = new Matrix();
  5754. Matrix.RotationXToRef(angle, result);
  5755. return result;
  5756. };
  5757. /**
  5758. * Creates a new matrix as the invert of a given matrix
  5759. * @param source defines the source matrix
  5760. * @returns the new matrix
  5761. */
  5762. Matrix.Invert = function (source) {
  5763. var result = new Matrix();
  5764. source.invertToRef(result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5769. * @param angle defines the angle (in radians) to use
  5770. * @param result defines the target matrix
  5771. */
  5772. Matrix.RotationXToRef = function (angle, result) {
  5773. var s = Math.sin(angle);
  5774. var c = Math.cos(angle);
  5775. result.m[0] = 1.0;
  5776. result.m[15] = 1.0;
  5777. result.m[5] = c;
  5778. result.m[10] = c;
  5779. result.m[9] = -s;
  5780. result.m[6] = s;
  5781. result.m[1] = 0.0;
  5782. result.m[2] = 0.0;
  5783. result.m[3] = 0.0;
  5784. result.m[4] = 0.0;
  5785. result.m[7] = 0.0;
  5786. result.m[8] = 0.0;
  5787. result.m[11] = 0.0;
  5788. result.m[12] = 0.0;
  5789. result.m[13] = 0.0;
  5790. result.m[14] = 0.0;
  5791. result._markAsUpdated();
  5792. };
  5793. /**
  5794. * Creates a new rotation matrix for "angle" radians around the Y axis
  5795. * @param angle defines the angle (in radians) to use
  5796. * @return the new matrix
  5797. */
  5798. Matrix.RotationY = function (angle) {
  5799. var result = new Matrix();
  5800. Matrix.RotationYToRef(angle, result);
  5801. return result;
  5802. };
  5803. /**
  5804. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5805. * @param angle defines the angle (in radians) to use
  5806. * @param result defines the target matrix
  5807. */
  5808. Matrix.RotationYToRef = function (angle, result) {
  5809. var s = Math.sin(angle);
  5810. var c = Math.cos(angle);
  5811. result.m[5] = 1.0;
  5812. result.m[15] = 1.0;
  5813. result.m[0] = c;
  5814. result.m[2] = -s;
  5815. result.m[8] = s;
  5816. result.m[10] = c;
  5817. result.m[1] = 0.0;
  5818. result.m[3] = 0.0;
  5819. result.m[4] = 0.0;
  5820. result.m[6] = 0.0;
  5821. result.m[7] = 0.0;
  5822. result.m[9] = 0.0;
  5823. result.m[11] = 0.0;
  5824. result.m[12] = 0.0;
  5825. result.m[13] = 0.0;
  5826. result.m[14] = 0.0;
  5827. result._markAsUpdated();
  5828. };
  5829. /**
  5830. * Creates a new rotation matrix for "angle" radians around the Z axis
  5831. * @param angle defines the angle (in radians) to use
  5832. * @return the new matrix
  5833. */
  5834. Matrix.RotationZ = function (angle) {
  5835. var result = new Matrix();
  5836. Matrix.RotationZToRef(angle, result);
  5837. return result;
  5838. };
  5839. /**
  5840. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationZToRef = function (angle, result) {
  5845. var s = Math.sin(angle);
  5846. var c = Math.cos(angle);
  5847. result.m[10] = 1.0;
  5848. result.m[15] = 1.0;
  5849. result.m[0] = c;
  5850. result.m[1] = s;
  5851. result.m[4] = -s;
  5852. result.m[5] = c;
  5853. result.m[2] = 0.0;
  5854. result.m[3] = 0.0;
  5855. result.m[6] = 0.0;
  5856. result.m[7] = 0.0;
  5857. result.m[8] = 0.0;
  5858. result.m[9] = 0.0;
  5859. result.m[11] = 0.0;
  5860. result.m[12] = 0.0;
  5861. result.m[13] = 0.0;
  5862. result.m[14] = 0.0;
  5863. result._markAsUpdated();
  5864. };
  5865. /**
  5866. * Creates a new rotation matrix for "angle" radians around the given axis
  5867. * @param axis defines the axis to use
  5868. * @param angle defines the angle (in radians) to use
  5869. * @return the new matrix
  5870. */
  5871. Matrix.RotationAxis = function (axis, angle) {
  5872. var result = Matrix.Zero();
  5873. Matrix.RotationAxisToRef(axis, angle, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5878. * @param axis defines the axis to use
  5879. * @param angle defines the angle (in radians) to use
  5880. * @param result defines the target matrix
  5881. */
  5882. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5883. var s = Math.sin(-angle);
  5884. var c = Math.cos(-angle);
  5885. var c1 = 1 - c;
  5886. axis.normalize();
  5887. result.m[0] = (axis.x * axis.x) * c1 + c;
  5888. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5889. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5890. result.m[3] = 0.0;
  5891. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5892. result.m[5] = (axis.y * axis.y) * c1 + c;
  5893. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5894. result.m[7] = 0.0;
  5895. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5896. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5897. result.m[10] = (axis.z * axis.z) * c1 + c;
  5898. result.m[11] = 0.0;
  5899. result.m[15] = 1.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a rotation matrix
  5904. * @param yaw defines the yaw angle in radians (Y axis)
  5905. * @param pitch defines the pitch angle in radians (X axis)
  5906. * @param roll defines the roll angle in radians (X axis)
  5907. * @returns the new rotation matrix
  5908. */
  5909. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5910. var result = new Matrix();
  5911. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5912. return result;
  5913. };
  5914. /**
  5915. * Creates a rotation matrix and stores it in a given matrix
  5916. * @param yaw defines the yaw angle in radians (Y axis)
  5917. * @param pitch defines the pitch angle in radians (X axis)
  5918. * @param roll defines the roll angle in radians (X axis)
  5919. * @param result defines the target matrix
  5920. */
  5921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5923. this._tempQuaternion.toRotationMatrix(result);
  5924. };
  5925. /**
  5926. * Creates a scaling matrix
  5927. * @param x defines the scale factor on X axis
  5928. * @param y defines the scale factor on Y axis
  5929. * @param z defines the scale factor on Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Scaling = function (x, y, z) {
  5933. var result = Matrix.Zero();
  5934. Matrix.ScalingToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a scaling matrix and stores it in a given matrix
  5939. * @param x defines the scale factor on X axis
  5940. * @param y defines the scale factor on Y axis
  5941. * @param z defines the scale factor on Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.ScalingToRef = function (x, y, z, result) {
  5945. result.m[0] = x;
  5946. result.m[1] = 0.0;
  5947. result.m[2] = 0.0;
  5948. result.m[3] = 0.0;
  5949. result.m[4] = 0.0;
  5950. result.m[5] = y;
  5951. result.m[6] = 0.0;
  5952. result.m[7] = 0.0;
  5953. result.m[8] = 0.0;
  5954. result.m[9] = 0.0;
  5955. result.m[10] = z;
  5956. result.m[11] = 0.0;
  5957. result.m[12] = 0.0;
  5958. result.m[13] = 0.0;
  5959. result.m[14] = 0.0;
  5960. result.m[15] = 1.0;
  5961. result._markAsUpdated();
  5962. };
  5963. /**
  5964. * Creates a translation matrix
  5965. * @param x defines the translation on X axis
  5966. * @param y defines the translation on Y axis
  5967. * @param z defines the translationon Z axis
  5968. * @returns the new matrix
  5969. */
  5970. Matrix.Translation = function (x, y, z) {
  5971. var result = Matrix.Identity();
  5972. Matrix.TranslationToRef(x, y, z, result);
  5973. return result;
  5974. };
  5975. /**
  5976. * Creates a translation matrix and stores it in a given matrix
  5977. * @param x defines the translation on X axis
  5978. * @param y defines the translation on Y axis
  5979. * @param z defines the translationon Z axis
  5980. * @param result defines the target matrix
  5981. */
  5982. Matrix.TranslationToRef = function (x, y, z, result) {
  5983. 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);
  5984. };
  5985. /**
  5986. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5987. * @param startValue defines the start value
  5988. * @param endValue defines the end value
  5989. * @param gradient defines the gradient factor
  5990. * @returns the new matrix
  5991. */
  5992. Matrix.Lerp = function (startValue, endValue, gradient) {
  5993. var result = Matrix.Zero();
  5994. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5995. return result;
  5996. };
  5997. /**
  5998. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5999. * @param startValue defines the start value
  6000. * @param endValue defines the end value
  6001. * @param gradient defines the gradient factor
  6002. * @param result defines the Matrix object where to store data
  6003. */
  6004. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6005. for (var index = 0; index < 16; index++) {
  6006. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6007. }
  6008. result._markAsUpdated();
  6009. };
  6010. /**
  6011. * Builds a new matrix whose values are computed by:
  6012. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6013. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6014. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6015. * @param startValue defines the first matrix
  6016. * @param endValue defines the second matrix
  6017. * @param gradient defines the gradient between the two matrices
  6018. * @returns the new matrix
  6019. */
  6020. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6021. var result = Matrix.Zero();
  6022. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6023. return result;
  6024. };
  6025. /**
  6026. * Update a matrix to values which are computed by:
  6027. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6028. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6029. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6030. * @param startValue defines the first matrix
  6031. * @param endValue defines the second matrix
  6032. * @param gradient defines the gradient between the two matrices
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6036. var startScale = MathTmp.Vector3[0];
  6037. var startRotation = MathTmp.Quaternion[0];
  6038. var startTranslation = MathTmp.Vector3[1];
  6039. startValue.decompose(startScale, startRotation, startTranslation);
  6040. var endScale = MathTmp.Vector3[2];
  6041. var endRotation = MathTmp.Quaternion[1];
  6042. var endTranslation = MathTmp.Vector3[3];
  6043. endValue.decompose(endScale, endRotation, endTranslation);
  6044. var resultScale = MathTmp.Vector3[4];
  6045. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6046. var resultRotation = MathTmp.Quaternion[2];
  6047. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6048. var resultTranslation = MathTmp.Vector3[5];
  6049. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6050. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6051. };
  6052. /**
  6053. * 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"
  6054. * This function works in left handed mode
  6055. * @param eye defines the final position of the entity
  6056. * @param target defines where the entity should look at
  6057. * @param up defines the up vector for the entity
  6058. * @returns the new matrix
  6059. */
  6060. Matrix.LookAtLH = function (eye, target, up) {
  6061. var result = Matrix.Zero();
  6062. Matrix.LookAtLHToRef(eye, target, up, result);
  6063. return result;
  6064. };
  6065. /**
  6066. * 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".
  6067. * This function works in left handed mode
  6068. * @param eye defines the final position of the entity
  6069. * @param target defines where the entity should look at
  6070. * @param up defines the up vector for the entity
  6071. * @param result defines the target matrix
  6072. */
  6073. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6074. // Z axis
  6075. target.subtractToRef(eye, this._zAxis);
  6076. this._zAxis.normalize();
  6077. // X axis
  6078. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6079. if (this._xAxis.lengthSquared() === 0) {
  6080. this._xAxis.x = 1.0;
  6081. }
  6082. else {
  6083. this._xAxis.normalize();
  6084. }
  6085. // Y axis
  6086. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6087. this._yAxis.normalize();
  6088. // Eye angles
  6089. var ex = -Vector3.Dot(this._xAxis, eye);
  6090. var ey = -Vector3.Dot(this._yAxis, eye);
  6091. var ez = -Vector3.Dot(this._zAxis, eye);
  6092. 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);
  6093. };
  6094. /**
  6095. * 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"
  6096. * This function works in right handed mode
  6097. * @param eye defines the final position of the entity
  6098. * @param target defines where the entity should look at
  6099. * @param up defines the up vector for the entity
  6100. * @returns the new matrix
  6101. */
  6102. Matrix.LookAtRH = function (eye, target, up) {
  6103. var result = Matrix.Zero();
  6104. Matrix.LookAtRHToRef(eye, target, up, result);
  6105. return result;
  6106. };
  6107. /**
  6108. * 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".
  6109. * This function works in right handed mode
  6110. * @param eye defines the final position of the entity
  6111. * @param target defines where the entity should look at
  6112. * @param up defines the up vector for the entity
  6113. * @param result defines the target matrix
  6114. */
  6115. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6116. // Z axis
  6117. eye.subtractToRef(target, this._zAxis);
  6118. this._zAxis.normalize();
  6119. // X axis
  6120. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6121. if (this._xAxis.lengthSquared() === 0) {
  6122. this._xAxis.x = 1.0;
  6123. }
  6124. else {
  6125. this._xAxis.normalize();
  6126. }
  6127. // Y axis
  6128. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6129. this._yAxis.normalize();
  6130. // Eye angles
  6131. var ex = -Vector3.Dot(this._xAxis, eye);
  6132. var ey = -Vector3.Dot(this._yAxis, eye);
  6133. var ez = -Vector3.Dot(this._zAxis, eye);
  6134. 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);
  6135. };
  6136. /**
  6137. * Create a left-handed orthographic projection matrix
  6138. * @param width defines the viewport width
  6139. * @param height defines the viewport height
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a left-handed orthographic projection matrix
  6143. */
  6144. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Store a left-handed orthographic projection to a given matrix
  6151. * @param width defines the viewport width
  6152. * @param height defines the viewport height
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. */
  6157. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6158. var n = znear;
  6159. var f = zfar;
  6160. var a = 2.0 / width;
  6161. var b = 2.0 / height;
  6162. var c = 2.0 / (f - n);
  6163. var d = -(f + n) / (f - n);
  6164. 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);
  6165. };
  6166. /**
  6167. * Create a left-handed orthographic projection matrix
  6168. * @param left defines the viewport left coordinate
  6169. * @param right defines the viewport right coordinate
  6170. * @param bottom defines the viewport bottom coordinate
  6171. * @param top defines the viewport top coordinate
  6172. * @param znear defines the near clip plane
  6173. * @param zfar defines the far clip plane
  6174. * @returns a new matrix as a left-handed orthographic projection matrix
  6175. */
  6176. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6177. var matrix = Matrix.Zero();
  6178. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6179. return matrix;
  6180. };
  6181. /**
  6182. * Stores a left-handed orthographic projection into a given matrix
  6183. * @param left defines the viewport left coordinate
  6184. * @param right defines the viewport right coordinate
  6185. * @param bottom defines the viewport bottom coordinate
  6186. * @param top defines the viewport top coordinate
  6187. * @param znear defines the near clip plane
  6188. * @param zfar defines the far clip plane
  6189. * @param result defines the target matrix
  6190. */
  6191. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6192. var n = znear;
  6193. var f = zfar;
  6194. var a = 2.0 / (right - left);
  6195. var b = 2.0 / (top - bottom);
  6196. var c = 2.0 / (f - n);
  6197. var d = -(f + n) / (f - n);
  6198. var i0 = (left + right) / (left - right);
  6199. var i1 = (top + bottom) / (bottom - top);
  6200. 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);
  6201. };
  6202. /**
  6203. * Creates a right-handed orthographic projection matrix
  6204. * @param left defines the viewport left coordinate
  6205. * @param right defines the viewport right coordinate
  6206. * @param bottom defines the viewport bottom coordinate
  6207. * @param top defines the viewport top coordinate
  6208. * @param znear defines the near clip plane
  6209. * @param zfar defines the far clip plane
  6210. * @returns a new matrix as a right-handed orthographic projection matrix
  6211. */
  6212. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6213. var matrix = Matrix.Zero();
  6214. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6215. return matrix;
  6216. };
  6217. /**
  6218. * Stores a right-handed orthographic projection into a given matrix
  6219. * @param left defines the viewport left coordinate
  6220. * @param right defines the viewport right coordinate
  6221. * @param bottom defines the viewport bottom coordinate
  6222. * @param top defines the viewport top coordinate
  6223. * @param znear defines the near clip plane
  6224. * @param zfar defines the far clip plane
  6225. * @param result defines the target matrix
  6226. */
  6227. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6228. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6229. result.m[10] *= -1.0;
  6230. };
  6231. /**
  6232. * Creates a left-handed perspective projection matrix
  6233. * @param width defines the viewport width
  6234. * @param height defines the viewport height
  6235. * @param znear defines the near clip plane
  6236. * @param zfar defines the far clip plane
  6237. * @returns a new matrix as a left-handed perspective projection matrix
  6238. */
  6239. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6240. var matrix = Matrix.Zero();
  6241. var n = znear;
  6242. var f = zfar;
  6243. var a = 2.0 * n / width;
  6244. var b = 2.0 * n / height;
  6245. var c = (f + n) / (f - n);
  6246. var d = -2.0 * f * n / (f - n);
  6247. 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);
  6248. return matrix;
  6249. };
  6250. /**
  6251. * Creates a left-handed perspective projection matrix
  6252. * @param fov defines the horizontal field of view
  6253. * @param aspect defines the aspect ratio
  6254. * @param znear defines the near clip plane
  6255. * @param zfar defines the far clip plane
  6256. * @returns a new matrix as a left-handed perspective projection matrix
  6257. */
  6258. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6259. var matrix = Matrix.Zero();
  6260. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6261. return matrix;
  6262. };
  6263. /**
  6264. * Stores a left-handed perspective projection into a given matrix
  6265. * @param fov defines the horizontal field of view
  6266. * @param aspect defines the aspect ratio
  6267. * @param znear defines the near clip plane
  6268. * @param zfar defines the far clip plane
  6269. * @param result defines the target matrix
  6270. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6271. */
  6272. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6273. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6274. var n = znear;
  6275. var f = zfar;
  6276. var t = 1.0 / (Math.tan(fov * 0.5));
  6277. var a = isVerticalFovFixed ? (t / aspect) : t;
  6278. var b = isVerticalFovFixed ? t : (t * aspect);
  6279. var c = (f + n) / (f - n);
  6280. var d = -2.0 * f * n / (f - n);
  6281. 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);
  6282. };
  6283. /**
  6284. * Creates a right-handed perspective projection matrix
  6285. * @param fov defines the horizontal field of view
  6286. * @param aspect defines the aspect ratio
  6287. * @param znear defines the near clip plane
  6288. * @param zfar defines the far clip plane
  6289. * @returns a new matrix as a right-handed perspective projection matrix
  6290. */
  6291. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6292. var matrix = Matrix.Zero();
  6293. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6294. return matrix;
  6295. };
  6296. /**
  6297. * Stores a right-handed perspective projection into a given matrix
  6298. * @param fov defines the horizontal field of view
  6299. * @param aspect defines the aspect ratio
  6300. * @param znear defines the near clip plane
  6301. * @param zfar defines the far clip plane
  6302. * @param result defines the target matrix
  6303. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6304. */
  6305. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6306. //alternatively this could be expressed as:
  6307. // m = PerspectiveFovLHToRef
  6308. // m[10] *= -1.0;
  6309. // m[11] *= -1.0;
  6310. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6311. var n = znear;
  6312. var f = zfar;
  6313. var t = 1.0 / (Math.tan(fov * 0.5));
  6314. var a = isVerticalFovFixed ? (t / aspect) : t;
  6315. var b = isVerticalFovFixed ? t : (t * aspect);
  6316. var c = -(f + n) / (f - n);
  6317. var d = -2 * f * n / (f - n);
  6318. 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);
  6319. };
  6320. /**
  6321. * Stores a perspective projection for WebVR info a given matrix
  6322. * @param fov defines the field of view
  6323. * @param znear defines the near clip plane
  6324. * @param zfar defines the far clip plane
  6325. * @param result defines the target matrix
  6326. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6327. */
  6328. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6329. if (rightHanded === void 0) { rightHanded = false; }
  6330. var rightHandedFactor = rightHanded ? -1 : 1;
  6331. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6332. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6333. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6334. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6335. var xScale = 2.0 / (leftTan + rightTan);
  6336. var yScale = 2.0 / (upTan + downTan);
  6337. result.m[0] = xScale;
  6338. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6339. result.m[5] = yScale;
  6340. result.m[6] = result.m[7] = 0.0;
  6341. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6342. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6343. result.m[10] = -zfar / (znear - zfar);
  6344. result.m[11] = 1.0 * rightHandedFactor;
  6345. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6346. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6347. result._markAsUpdated();
  6348. };
  6349. /**
  6350. * Computes a complete transformation matrix
  6351. * @param viewport defines the viewport to use
  6352. * @param world defines the world matrix
  6353. * @param view defines the view matrix
  6354. * @param projection defines the projection matrix
  6355. * @param zmin defines the near clip plane
  6356. * @param zmax defines the far clip plane
  6357. * @returns the transformation matrix
  6358. */
  6359. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6360. var cw = viewport.width;
  6361. var ch = viewport.height;
  6362. var cx = viewport.x;
  6363. var cy = viewport.y;
  6364. 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);
  6365. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6366. };
  6367. /**
  6368. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6369. * @param matrix defines the matrix to use
  6370. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6371. */
  6372. Matrix.GetAsMatrix2x2 = function (matrix) {
  6373. return new Float32Array([
  6374. matrix.m[0], matrix.m[1],
  6375. matrix.m[4], matrix.m[5]
  6376. ]);
  6377. };
  6378. /**
  6379. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6380. * @param matrix defines the matrix to use
  6381. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6382. */
  6383. Matrix.GetAsMatrix3x3 = function (matrix) {
  6384. return new Float32Array([
  6385. matrix.m[0], matrix.m[1], matrix.m[2],
  6386. matrix.m[4], matrix.m[5], matrix.m[6],
  6387. matrix.m[8], matrix.m[9], matrix.m[10]
  6388. ]);
  6389. };
  6390. /**
  6391. * Compute the transpose of a given matrix
  6392. * @param matrix defines the matrix to transpose
  6393. * @returns the new matrix
  6394. */
  6395. Matrix.Transpose = function (matrix) {
  6396. var result = new Matrix();
  6397. Matrix.TransposeToRef(matrix, result);
  6398. return result;
  6399. };
  6400. /**
  6401. * Compute the transpose of a matrix and store it in a target matrix
  6402. * @param matrix defines the matrix to transpose
  6403. * @param result defines the target matrix
  6404. */
  6405. Matrix.TransposeToRef = function (matrix, result) {
  6406. result.m[0] = matrix.m[0];
  6407. result.m[1] = matrix.m[4];
  6408. result.m[2] = matrix.m[8];
  6409. result.m[3] = matrix.m[12];
  6410. result.m[4] = matrix.m[1];
  6411. result.m[5] = matrix.m[5];
  6412. result.m[6] = matrix.m[9];
  6413. result.m[7] = matrix.m[13];
  6414. result.m[8] = matrix.m[2];
  6415. result.m[9] = matrix.m[6];
  6416. result.m[10] = matrix.m[10];
  6417. result.m[11] = matrix.m[14];
  6418. result.m[12] = matrix.m[3];
  6419. result.m[13] = matrix.m[7];
  6420. result.m[14] = matrix.m[11];
  6421. result.m[15] = matrix.m[15];
  6422. };
  6423. /**
  6424. * Computes a reflection matrix from a plane
  6425. * @param plane defines the reflection plane
  6426. * @returns a new matrix
  6427. */
  6428. Matrix.Reflection = function (plane) {
  6429. var matrix = new Matrix();
  6430. Matrix.ReflectionToRef(plane, matrix);
  6431. return matrix;
  6432. };
  6433. /**
  6434. * Computes a reflection matrix from a plane
  6435. * @param plane defines the reflection plane
  6436. * @param result defines the target matrix
  6437. */
  6438. Matrix.ReflectionToRef = function (plane, result) {
  6439. plane.normalize();
  6440. var x = plane.normal.x;
  6441. var y = plane.normal.y;
  6442. var z = plane.normal.z;
  6443. var temp = -2 * x;
  6444. var temp2 = -2 * y;
  6445. var temp3 = -2 * z;
  6446. result.m[0] = (temp * x) + 1;
  6447. result.m[1] = temp2 * x;
  6448. result.m[2] = temp3 * x;
  6449. result.m[3] = 0.0;
  6450. result.m[4] = temp * y;
  6451. result.m[5] = (temp2 * y) + 1;
  6452. result.m[6] = temp3 * y;
  6453. result.m[7] = 0.0;
  6454. result.m[8] = temp * z;
  6455. result.m[9] = temp2 * z;
  6456. result.m[10] = (temp3 * z) + 1;
  6457. result.m[11] = 0.0;
  6458. result.m[12] = temp * plane.d;
  6459. result.m[13] = temp2 * plane.d;
  6460. result.m[14] = temp3 * plane.d;
  6461. result.m[15] = 1.0;
  6462. result._markAsUpdated();
  6463. };
  6464. /**
  6465. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6466. * @param xaxis defines the value of the 1st axis
  6467. * @param yaxis defines the value of the 2nd axis
  6468. * @param zaxis defines the value of the 3rd axis
  6469. * @param result defines the target matrix
  6470. */
  6471. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6472. result.m[0] = xaxis.x;
  6473. result.m[1] = xaxis.y;
  6474. result.m[2] = xaxis.z;
  6475. result.m[3] = 0.0;
  6476. result.m[4] = yaxis.x;
  6477. result.m[5] = yaxis.y;
  6478. result.m[6] = yaxis.z;
  6479. result.m[7] = 0.0;
  6480. result.m[8] = zaxis.x;
  6481. result.m[9] = zaxis.y;
  6482. result.m[10] = zaxis.z;
  6483. result.m[11] = 0.0;
  6484. result.m[12] = 0.0;
  6485. result.m[13] = 0.0;
  6486. result.m[14] = 0.0;
  6487. result.m[15] = 1.0;
  6488. result._markAsUpdated();
  6489. };
  6490. /**
  6491. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6492. * @param quat defines the quaternion to use
  6493. * @param result defines the target matrix
  6494. */
  6495. Matrix.FromQuaternionToRef = function (quat, result) {
  6496. var xx = quat.x * quat.x;
  6497. var yy = quat.y * quat.y;
  6498. var zz = quat.z * quat.z;
  6499. var xy = quat.x * quat.y;
  6500. var zw = quat.z * quat.w;
  6501. var zx = quat.z * quat.x;
  6502. var yw = quat.y * quat.w;
  6503. var yz = quat.y * quat.z;
  6504. var xw = quat.x * quat.w;
  6505. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6506. result.m[1] = 2.0 * (xy + zw);
  6507. result.m[2] = 2.0 * (zx - yw);
  6508. result.m[3] = 0.0;
  6509. result.m[4] = 2.0 * (xy - zw);
  6510. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6511. result.m[6] = 2.0 * (yz + xw);
  6512. result.m[7] = 0.0;
  6513. result.m[8] = 2.0 * (zx + yw);
  6514. result.m[9] = 2.0 * (yz - xw);
  6515. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6516. result.m[11] = 0.0;
  6517. result.m[12] = 0.0;
  6518. result.m[13] = 0.0;
  6519. result.m[14] = 0.0;
  6520. result.m[15] = 1.0;
  6521. result._markAsUpdated();
  6522. };
  6523. Matrix._tempQuaternion = new Quaternion();
  6524. Matrix._xAxis = Vector3.Zero();
  6525. Matrix._yAxis = Vector3.Zero();
  6526. Matrix._zAxis = Vector3.Zero();
  6527. Matrix._updateFlagSeed = 0;
  6528. Matrix._identityReadOnly = Matrix.Identity();
  6529. return Matrix;
  6530. }());
  6531. BABYLON.Matrix = Matrix;
  6532. var Plane = /** @class */ (function () {
  6533. /**
  6534. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6535. */
  6536. function Plane(a, b, c, d) {
  6537. this.normal = new Vector3(a, b, c);
  6538. this.d = d;
  6539. }
  6540. /**
  6541. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6542. */
  6543. Plane.prototype.asArray = function () {
  6544. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6545. };
  6546. // Methods
  6547. /**
  6548. * Returns a new plane copied from the current Plane.
  6549. */
  6550. Plane.prototype.clone = function () {
  6551. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6552. };
  6553. /**
  6554. * Returns the string "Plane".
  6555. */
  6556. Plane.prototype.getClassName = function () {
  6557. return "Plane";
  6558. };
  6559. /**
  6560. * Returns the Plane hash code.
  6561. */
  6562. Plane.prototype.getHashCode = function () {
  6563. var hash = this.normal.getHashCode();
  6564. hash = (hash * 397) ^ (this.d || 0);
  6565. return hash;
  6566. };
  6567. /**
  6568. * Normalize the current Plane in place.
  6569. * Returns the updated Plane.
  6570. */
  6571. Plane.prototype.normalize = function () {
  6572. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6573. var magnitude = 0.0;
  6574. if (norm !== 0) {
  6575. magnitude = 1.0 / norm;
  6576. }
  6577. this.normal.x *= magnitude;
  6578. this.normal.y *= magnitude;
  6579. this.normal.z *= magnitude;
  6580. this.d *= magnitude;
  6581. return this;
  6582. };
  6583. /**
  6584. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6585. */
  6586. Plane.prototype.transform = function (transformation) {
  6587. var transposedMatrix = Matrix.Transpose(transformation);
  6588. var x = this.normal.x;
  6589. var y = this.normal.y;
  6590. var z = this.normal.z;
  6591. var d = this.d;
  6592. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6593. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6594. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6595. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6596. return new Plane(normalX, normalY, normalZ, finalD);
  6597. };
  6598. /**
  6599. * Returns the dot product (float) of the point coordinates and the plane normal.
  6600. */
  6601. Plane.prototype.dotCoordinate = function (point) {
  6602. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6603. };
  6604. /**
  6605. * Updates the current Plane from the plane defined by the three given points.
  6606. * Returns the updated Plane.
  6607. */
  6608. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6609. var x1 = point2.x - point1.x;
  6610. var y1 = point2.y - point1.y;
  6611. var z1 = point2.z - point1.z;
  6612. var x2 = point3.x - point1.x;
  6613. var y2 = point3.y - point1.y;
  6614. var z2 = point3.z - point1.z;
  6615. var yz = (y1 * z2) - (z1 * y2);
  6616. var xz = (z1 * x2) - (x1 * z2);
  6617. var xy = (x1 * y2) - (y1 * x2);
  6618. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6619. var invPyth;
  6620. if (pyth !== 0) {
  6621. invPyth = 1.0 / pyth;
  6622. }
  6623. else {
  6624. invPyth = 0.0;
  6625. }
  6626. this.normal.x = yz * invPyth;
  6627. this.normal.y = xz * invPyth;
  6628. this.normal.z = xy * invPyth;
  6629. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6630. return this;
  6631. };
  6632. /**
  6633. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6634. */
  6635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6636. var dot = Vector3.Dot(this.normal, direction);
  6637. return (dot <= epsilon);
  6638. };
  6639. /**
  6640. * Returns the signed distance (float) from the given point to the Plane.
  6641. */
  6642. Plane.prototype.signedDistanceTo = function (point) {
  6643. return Vector3.Dot(point, this.normal) + this.d;
  6644. };
  6645. // Statics
  6646. /**
  6647. * Returns a new Plane from the given array.
  6648. */
  6649. Plane.FromArray = function (array) {
  6650. return new Plane(array[0], array[1], array[2], array[3]);
  6651. };
  6652. /**
  6653. * Returns a new Plane defined by the three given points.
  6654. */
  6655. Plane.FromPoints = function (point1, point2, point3) {
  6656. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6657. result.copyFromPoints(point1, point2, point3);
  6658. return result;
  6659. };
  6660. /**
  6661. * Returns a new Plane the normal vector to this plane at the given origin point.
  6662. * Note : the vector "normal" is updated because normalized.
  6663. */
  6664. Plane.FromPositionAndNormal = function (origin, normal) {
  6665. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6666. normal.normalize();
  6667. result.normal = normal;
  6668. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6669. return result;
  6670. };
  6671. /**
  6672. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6673. */
  6674. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6675. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6676. return Vector3.Dot(point, normal) + d;
  6677. };
  6678. return Plane;
  6679. }());
  6680. BABYLON.Plane = Plane;
  6681. var Viewport = /** @class */ (function () {
  6682. /**
  6683. * Creates a Viewport object located at (x, y) and sized (width, height).
  6684. */
  6685. function Viewport(x, y, width, height) {
  6686. this.x = x;
  6687. this.y = y;
  6688. this.width = width;
  6689. this.height = height;
  6690. }
  6691. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6692. if (renderWidthOrEngine.getRenderWidth) {
  6693. var engine = renderWidthOrEngine;
  6694. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6695. }
  6696. var renderWidth = renderWidthOrEngine;
  6697. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6698. };
  6699. /**
  6700. * Returns a new Viewport copied from the current one.
  6701. */
  6702. Viewport.prototype.clone = function () {
  6703. return new Viewport(this.x, this.y, this.width, this.height);
  6704. };
  6705. return Viewport;
  6706. }());
  6707. BABYLON.Viewport = Viewport;
  6708. var Frustum = /** @class */ (function () {
  6709. function Frustum() {
  6710. }
  6711. /**
  6712. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6713. */
  6714. Frustum.GetPlanes = function (transform) {
  6715. var frustumPlanes = [];
  6716. for (var index = 0; index < 6; index++) {
  6717. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6718. }
  6719. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6720. return frustumPlanes;
  6721. };
  6722. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6723. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6724. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6725. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6726. frustumPlane.d = transform.m[15] + transform.m[14];
  6727. frustumPlane.normalize();
  6728. };
  6729. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6730. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6731. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6732. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6733. frustumPlane.d = transform.m[15] - transform.m[14];
  6734. frustumPlane.normalize();
  6735. };
  6736. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6737. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6738. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6739. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6740. frustumPlane.d = transform.m[15] + transform.m[12];
  6741. frustumPlane.normalize();
  6742. };
  6743. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6744. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6745. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6746. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6747. frustumPlane.d = transform.m[15] - transform.m[12];
  6748. frustumPlane.normalize();
  6749. };
  6750. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6751. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6752. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6753. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6754. frustumPlane.d = transform.m[15] - transform.m[13];
  6755. frustumPlane.normalize();
  6756. };
  6757. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6758. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6759. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6760. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6761. frustumPlane.d = transform.m[15] + transform.m[13];
  6762. frustumPlane.normalize();
  6763. };
  6764. /**
  6765. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6766. */
  6767. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6768. // Near
  6769. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6770. // Far
  6771. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6772. // Left
  6773. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6774. // Right
  6775. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6776. // Top
  6777. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6778. // Bottom
  6779. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6780. };
  6781. return Frustum;
  6782. }());
  6783. BABYLON.Frustum = Frustum;
  6784. /** Defines supported spaces */
  6785. var Space;
  6786. (function (Space) {
  6787. /** Local (object) space */
  6788. Space[Space["LOCAL"] = 0] = "LOCAL";
  6789. /** World space */
  6790. Space[Space["WORLD"] = 1] = "WORLD";
  6791. /** Bone space */
  6792. Space[Space["BONE"] = 2] = "BONE";
  6793. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6794. /** Defines the 3 main axes */
  6795. var Axis = /** @class */ (function () {
  6796. function Axis() {
  6797. }
  6798. /** X axis */
  6799. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6800. /** Y axis */
  6801. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6802. /** Z axis */
  6803. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6804. return Axis;
  6805. }());
  6806. BABYLON.Axis = Axis;
  6807. ;
  6808. var BezierCurve = /** @class */ (function () {
  6809. function BezierCurve() {
  6810. }
  6811. /**
  6812. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6813. */
  6814. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6815. // Extract X (which is equal to time here)
  6816. var f0 = 1 - 3 * x2 + 3 * x1;
  6817. var f1 = 3 * x2 - 6 * x1;
  6818. var f2 = 3 * x1;
  6819. var refinedT = t;
  6820. for (var i = 0; i < 5; i++) {
  6821. var refinedT2 = refinedT * refinedT;
  6822. var refinedT3 = refinedT2 * refinedT;
  6823. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6824. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6825. refinedT -= (x - t) * slope;
  6826. refinedT = Math.min(1, Math.max(0, refinedT));
  6827. }
  6828. // Resolve cubic bezier for the given x
  6829. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6830. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6831. Math.pow(refinedT, 3);
  6832. };
  6833. return BezierCurve;
  6834. }());
  6835. BABYLON.BezierCurve = BezierCurve;
  6836. /**
  6837. * Defines potential orientation for back face culling
  6838. */
  6839. var Orientation;
  6840. (function (Orientation) {
  6841. /**
  6842. * Clockwise
  6843. */
  6844. Orientation[Orientation["CW"] = 0] = "CW";
  6845. /** Counter clockwise */
  6846. Orientation[Orientation["CCW"] = 1] = "CCW";
  6847. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6848. /**
  6849. * Defines angle representation
  6850. */
  6851. var Angle = /** @class */ (function () {
  6852. /**
  6853. * Creates an Angle object of "radians" radians (float).
  6854. */
  6855. function Angle(radians) {
  6856. this._radians = radians;
  6857. if (this._radians < 0.0)
  6858. this._radians += (2.0 * Math.PI);
  6859. }
  6860. /**
  6861. * Get value in degrees
  6862. * @returns the Angle value in degrees (float)
  6863. */
  6864. Angle.prototype.degrees = function () {
  6865. return this._radians * 180.0 / Math.PI;
  6866. };
  6867. /**
  6868. * Get value in radians
  6869. * @returns the Angle value in radians (float)
  6870. */
  6871. Angle.prototype.radians = function () {
  6872. return this._radians;
  6873. };
  6874. /**
  6875. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6876. * @param a defines first vector
  6877. * @param b defines second vector
  6878. * @returns a new Angle
  6879. */
  6880. Angle.BetweenTwoPoints = function (a, b) {
  6881. var delta = b.subtract(a);
  6882. var theta = Math.atan2(delta.y, delta.x);
  6883. return new Angle(theta);
  6884. };
  6885. /**
  6886. * Gets a new Angle object from the given float in radians
  6887. * @param radians defines the angle value in radians
  6888. * @returns a new Angle
  6889. */
  6890. Angle.FromRadians = function (radians) {
  6891. return new Angle(radians);
  6892. };
  6893. /**
  6894. * Gets a new Angle object from the given float in degrees
  6895. * @param degrees defines the angle value in degrees
  6896. * @returns a new Angle
  6897. */
  6898. Angle.FromDegrees = function (degrees) {
  6899. return new Angle(degrees * Math.PI / 180.0);
  6900. };
  6901. return Angle;
  6902. }());
  6903. BABYLON.Angle = Angle;
  6904. var Arc2 = /** @class */ (function () {
  6905. /**
  6906. * Creates an Arc object from the three given points : start, middle and end.
  6907. */
  6908. function Arc2(startPoint, midPoint, endPoint) {
  6909. this.startPoint = startPoint;
  6910. this.midPoint = midPoint;
  6911. this.endPoint = endPoint;
  6912. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6913. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6914. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6915. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6916. 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);
  6917. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6918. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6919. var a1 = this.startAngle.degrees();
  6920. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6921. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6922. // angles correction
  6923. if (a2 - a1 > +180.0)
  6924. a2 -= 360.0;
  6925. if (a2 - a1 < -180.0)
  6926. a2 += 360.0;
  6927. if (a3 - a2 > +180.0)
  6928. a3 -= 360.0;
  6929. if (a3 - a2 < -180.0)
  6930. a3 += 360.0;
  6931. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6932. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6933. }
  6934. return Arc2;
  6935. }());
  6936. BABYLON.Arc2 = Arc2;
  6937. var Path2 = /** @class */ (function () {
  6938. /**
  6939. * Creates a Path2 object from the starting 2D coordinates x and y.
  6940. */
  6941. function Path2(x, y) {
  6942. this._points = new Array();
  6943. this._length = 0.0;
  6944. this.closed = false;
  6945. this._points.push(new Vector2(x, y));
  6946. }
  6947. /**
  6948. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6949. * Returns the updated Path2.
  6950. */
  6951. Path2.prototype.addLineTo = function (x, y) {
  6952. if (this.closed) {
  6953. return this;
  6954. }
  6955. var newPoint = new Vector2(x, y);
  6956. var previousPoint = this._points[this._points.length - 1];
  6957. this._points.push(newPoint);
  6958. this._length += newPoint.subtract(previousPoint).length();
  6959. return this;
  6960. };
  6961. /**
  6962. * 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.
  6963. * Returns the updated Path2.
  6964. */
  6965. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6966. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6967. if (this.closed) {
  6968. return this;
  6969. }
  6970. var startPoint = this._points[this._points.length - 1];
  6971. var midPoint = new Vector2(midX, midY);
  6972. var endPoint = new Vector2(endX, endY);
  6973. var arc = new Arc2(startPoint, midPoint, endPoint);
  6974. var increment = arc.angle.radians() / numberOfSegments;
  6975. if (arc.orientation === Orientation.CW)
  6976. increment *= -1;
  6977. var currentAngle = arc.startAngle.radians() + increment;
  6978. for (var i = 0; i < numberOfSegments; i++) {
  6979. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6980. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6981. this.addLineTo(x, y);
  6982. currentAngle += increment;
  6983. }
  6984. return this;
  6985. };
  6986. /**
  6987. * Closes the Path2.
  6988. * Returns the Path2.
  6989. */
  6990. Path2.prototype.close = function () {
  6991. this.closed = true;
  6992. return this;
  6993. };
  6994. /**
  6995. * Returns the Path2 total length (float).
  6996. */
  6997. Path2.prototype.length = function () {
  6998. var result = this._length;
  6999. if (!this.closed) {
  7000. var lastPoint = this._points[this._points.length - 1];
  7001. var firstPoint = this._points[0];
  7002. result += (firstPoint.subtract(lastPoint).length());
  7003. }
  7004. return result;
  7005. };
  7006. /**
  7007. * Returns the Path2 internal array of points.
  7008. */
  7009. Path2.prototype.getPoints = function () {
  7010. return this._points;
  7011. };
  7012. /**
  7013. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7014. */
  7015. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7016. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7017. return Vector2.Zero();
  7018. }
  7019. var lengthPosition = normalizedLengthPosition * this.length();
  7020. var previousOffset = 0;
  7021. for (var i = 0; i < this._points.length; i++) {
  7022. var j = (i + 1) % this._points.length;
  7023. var a = this._points[i];
  7024. var b = this._points[j];
  7025. var bToA = b.subtract(a);
  7026. var nextOffset = (bToA.length() + previousOffset);
  7027. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7028. var dir = bToA.normalize();
  7029. var localOffset = lengthPosition - previousOffset;
  7030. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7031. }
  7032. previousOffset = nextOffset;
  7033. }
  7034. return Vector2.Zero();
  7035. };
  7036. /**
  7037. * Returns a new Path2 starting at the coordinates (x, y).
  7038. */
  7039. Path2.StartingAt = function (x, y) {
  7040. return new Path2(x, y);
  7041. };
  7042. return Path2;
  7043. }());
  7044. BABYLON.Path2 = Path2;
  7045. var Path3D = /** @class */ (function () {
  7046. /**
  7047. * new Path3D(path, normal, raw)
  7048. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7049. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7050. * path : an array of Vector3, the curve axis of the Path3D
  7051. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7052. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7053. */
  7054. function Path3D(path, firstNormal, raw) {
  7055. if (firstNormal === void 0) { firstNormal = null; }
  7056. this.path = path;
  7057. this._curve = new Array();
  7058. this._distances = new Array();
  7059. this._tangents = new Array();
  7060. this._normals = new Array();
  7061. this._binormals = new Array();
  7062. for (var p = 0; p < path.length; p++) {
  7063. this._curve[p] = path[p].clone(); // hard copy
  7064. }
  7065. this._raw = raw || false;
  7066. this._compute(firstNormal);
  7067. }
  7068. /**
  7069. * Returns the Path3D array of successive Vector3 designing its curve.
  7070. */
  7071. Path3D.prototype.getCurve = function () {
  7072. return this._curve;
  7073. };
  7074. /**
  7075. * Returns an array populated with tangent vectors on each Path3D curve point.
  7076. */
  7077. Path3D.prototype.getTangents = function () {
  7078. return this._tangents;
  7079. };
  7080. /**
  7081. * Returns an array populated with normal vectors on each Path3D curve point.
  7082. */
  7083. Path3D.prototype.getNormals = function () {
  7084. return this._normals;
  7085. };
  7086. /**
  7087. * Returns an array populated with binormal vectors on each Path3D curve point.
  7088. */
  7089. Path3D.prototype.getBinormals = function () {
  7090. return this._binormals;
  7091. };
  7092. /**
  7093. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7094. */
  7095. Path3D.prototype.getDistances = function () {
  7096. return this._distances;
  7097. };
  7098. /**
  7099. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7100. * Returns the same object updated.
  7101. */
  7102. Path3D.prototype.update = function (path, firstNormal) {
  7103. if (firstNormal === void 0) { firstNormal = null; }
  7104. for (var p = 0; p < path.length; p++) {
  7105. this._curve[p].x = path[p].x;
  7106. this._curve[p].y = path[p].y;
  7107. this._curve[p].z = path[p].z;
  7108. }
  7109. this._compute(firstNormal);
  7110. return this;
  7111. };
  7112. // private function compute() : computes tangents, normals and binormals
  7113. Path3D.prototype._compute = function (firstNormal) {
  7114. var l = this._curve.length;
  7115. // first and last tangents
  7116. this._tangents[0] = this._getFirstNonNullVector(0);
  7117. if (!this._raw) {
  7118. this._tangents[0].normalize();
  7119. }
  7120. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7121. if (!this._raw) {
  7122. this._tangents[l - 1].normalize();
  7123. }
  7124. // normals and binormals at first point : arbitrary vector with _normalVector()
  7125. var tg0 = this._tangents[0];
  7126. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7127. this._normals[0] = pp0;
  7128. if (!this._raw) {
  7129. this._normals[0].normalize();
  7130. }
  7131. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7132. if (!this._raw) {
  7133. this._binormals[0].normalize();
  7134. }
  7135. this._distances[0] = 0.0;
  7136. // normals and binormals : next points
  7137. var prev; // previous vector (segment)
  7138. var cur; // current vector (segment)
  7139. var curTang; // current tangent
  7140. // previous normal
  7141. var prevBinor; // previous binormal
  7142. for (var i = 1; i < l; i++) {
  7143. // tangents
  7144. prev = this._getLastNonNullVector(i);
  7145. if (i < l - 1) {
  7146. cur = this._getFirstNonNullVector(i);
  7147. this._tangents[i] = prev.add(cur);
  7148. this._tangents[i].normalize();
  7149. }
  7150. this._distances[i] = this._distances[i - 1] + prev.length();
  7151. // normals and binormals
  7152. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7153. curTang = this._tangents[i];
  7154. prevBinor = this._binormals[i - 1];
  7155. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7156. if (!this._raw) {
  7157. this._normals[i].normalize();
  7158. }
  7159. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7160. if (!this._raw) {
  7161. this._binormals[i].normalize();
  7162. }
  7163. }
  7164. };
  7165. // private function getFirstNonNullVector(index)
  7166. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7167. Path3D.prototype._getFirstNonNullVector = function (index) {
  7168. var i = 1;
  7169. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7170. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7171. i++;
  7172. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7173. }
  7174. return nNVector;
  7175. };
  7176. // private function getLastNonNullVector(index)
  7177. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7178. Path3D.prototype._getLastNonNullVector = function (index) {
  7179. var i = 1;
  7180. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7181. while (nLVector.length() === 0 && index > i + 1) {
  7182. i++;
  7183. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7184. }
  7185. return nLVector;
  7186. };
  7187. // private function normalVector(v0, vt, va) :
  7188. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7189. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7190. Path3D.prototype._normalVector = function (v0, vt, va) {
  7191. var normal0;
  7192. var tgl = vt.length();
  7193. if (tgl === 0.0) {
  7194. tgl = 1.0;
  7195. }
  7196. if (va === undefined || va === null) {
  7197. var point;
  7198. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7199. point = new Vector3(0.0, -1.0, 0.0);
  7200. }
  7201. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7202. point = new Vector3(1.0, 0.0, 0.0);
  7203. }
  7204. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7205. point = new Vector3(0.0, 0.0, 1.0);
  7206. }
  7207. else {
  7208. point = Vector3.Zero();
  7209. }
  7210. normal0 = Vector3.Cross(vt, point);
  7211. }
  7212. else {
  7213. normal0 = Vector3.Cross(vt, va);
  7214. Vector3.CrossToRef(normal0, vt, normal0);
  7215. }
  7216. normal0.normalize();
  7217. return normal0;
  7218. };
  7219. return Path3D;
  7220. }());
  7221. BABYLON.Path3D = Path3D;
  7222. var Curve3 = /** @class */ (function () {
  7223. /**
  7224. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7225. * A Curve3 is designed from a series of successive Vector3.
  7226. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7227. */
  7228. function Curve3(points) {
  7229. this._length = 0.0;
  7230. this._points = points;
  7231. this._length = this._computeLength(points);
  7232. }
  7233. /**
  7234. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7235. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7236. * @param v1 (Vector3) the control point
  7237. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7238. * @param nbPoints (integer) the wanted number of points in the curve
  7239. */
  7240. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7241. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7242. var bez = new Array();
  7243. var equation = function (t, val0, val1, val2) {
  7244. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7245. return res;
  7246. };
  7247. for (var i = 0; i <= nbPoints; i++) {
  7248. 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)));
  7249. }
  7250. return new Curve3(bez);
  7251. };
  7252. /**
  7253. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7254. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7255. * @param v1 (Vector3) the first control point
  7256. * @param v2 (Vector3) the second control point
  7257. * @param v3 (Vector3) the end point of the Cubic Bezier
  7258. * @param nbPoints (integer) the wanted number of points in the curve
  7259. */
  7260. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7261. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7262. var bez = new Array();
  7263. var equation = function (t, val0, val1, val2, val3) {
  7264. 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;
  7265. return res;
  7266. };
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. 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)));
  7269. }
  7270. return new Curve3(bez);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7274. * @param p1 (Vector3) the origin point of the Hermite Spline
  7275. * @param t1 (Vector3) the tangent vector at the origin point
  7276. * @param p2 (Vector3) the end point of the Hermite Spline
  7277. * @param t2 (Vector3) the tangent vector at the end point
  7278. * @param nbPoints (integer) the wanted number of points in the curve
  7279. */
  7280. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7281. var hermite = new Array();
  7282. var step = 1.0 / nbPoints;
  7283. for (var i = 0; i <= nbPoints; i++) {
  7284. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7285. }
  7286. return new Curve3(hermite);
  7287. };
  7288. /**
  7289. * Returns a Curve3 object along a CatmullRom Spline curve :
  7290. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7291. * @param nbPoints (integer) the wanted number of points between each curve control points
  7292. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7293. */
  7294. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7295. var catmullRom = new Array();
  7296. var step = 1.0 / nbPoints;
  7297. var amount = 0.0;
  7298. if (closed) {
  7299. var pointsCount = points.length;
  7300. for (var i = 0; i < pointsCount; i++) {
  7301. amount = 0;
  7302. for (var c = 0; c < nbPoints; c++) {
  7303. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7304. amount += step;
  7305. }
  7306. }
  7307. catmullRom.push(catmullRom[0]);
  7308. }
  7309. else {
  7310. var totalPoints = new Array();
  7311. totalPoints.push(points[0].clone());
  7312. Array.prototype.push.apply(totalPoints, points);
  7313. totalPoints.push(points[points.length - 1].clone());
  7314. for (var i = 0; i < totalPoints.length - 3; i++) {
  7315. amount = 0;
  7316. for (var c = 0; c < nbPoints; c++) {
  7317. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7318. amount += step;
  7319. }
  7320. }
  7321. i--;
  7322. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7323. }
  7324. return new Curve3(catmullRom);
  7325. };
  7326. /**
  7327. * Returns the Curve3 stored array of successive Vector3
  7328. */
  7329. Curve3.prototype.getPoints = function () {
  7330. return this._points;
  7331. };
  7332. /**
  7333. * Returns the computed length (float) of the curve.
  7334. */
  7335. Curve3.prototype.length = function () {
  7336. return this._length;
  7337. };
  7338. /**
  7339. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7340. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7341. * curveA and curveB keep unchanged.
  7342. */
  7343. Curve3.prototype.continue = function (curve) {
  7344. var lastPoint = this._points[this._points.length - 1];
  7345. var continuedPoints = this._points.slice();
  7346. var curvePoints = curve.getPoints();
  7347. for (var i = 1; i < curvePoints.length; i++) {
  7348. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7349. }
  7350. var continuedCurve = new Curve3(continuedPoints);
  7351. return continuedCurve;
  7352. };
  7353. Curve3.prototype._computeLength = function (path) {
  7354. var l = 0;
  7355. for (var i = 1; i < path.length; i++) {
  7356. l += (path[i].subtract(path[i - 1])).length();
  7357. }
  7358. return l;
  7359. };
  7360. return Curve3;
  7361. }());
  7362. BABYLON.Curve3 = Curve3;
  7363. // Vertex formats
  7364. var PositionNormalVertex = /** @class */ (function () {
  7365. function PositionNormalVertex(position, normal) {
  7366. if (position === void 0) { position = Vector3.Zero(); }
  7367. if (normal === void 0) { normal = Vector3.Up(); }
  7368. this.position = position;
  7369. this.normal = normal;
  7370. }
  7371. PositionNormalVertex.prototype.clone = function () {
  7372. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7373. };
  7374. return PositionNormalVertex;
  7375. }());
  7376. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7377. var PositionNormalTextureVertex = /** @class */ (function () {
  7378. function PositionNormalTextureVertex(position, normal, uv) {
  7379. if (position === void 0) { position = Vector3.Zero(); }
  7380. if (normal === void 0) { normal = Vector3.Up(); }
  7381. if (uv === void 0) { uv = Vector2.Zero(); }
  7382. this.position = position;
  7383. this.normal = normal;
  7384. this.uv = uv;
  7385. }
  7386. PositionNormalTextureVertex.prototype.clone = function () {
  7387. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7388. };
  7389. return PositionNormalTextureVertex;
  7390. }());
  7391. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7392. // Temporary pre-allocated objects for engine internal use
  7393. // usage in any internal function :
  7394. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7395. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7396. var Tmp = /** @class */ (function () {
  7397. function Tmp() {
  7398. }
  7399. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7400. Tmp.Color4 = [new Color4(0, 0, 0, 0)];
  7401. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7402. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7403. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7404. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7405. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7406. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7407. Matrix.Zero(), Matrix.Zero(),
  7408. Matrix.Zero(), Matrix.Zero(),
  7409. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7410. return Tmp;
  7411. }());
  7412. BABYLON.Tmp = Tmp;
  7413. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7414. var MathTmp = /** @class */ (function () {
  7415. function MathTmp() {
  7416. }
  7417. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7418. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7419. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7420. return MathTmp;
  7421. }());
  7422. })(BABYLON || (BABYLON = {}));
  7423. //# sourceMappingURL=babylon.math.js.map
  7424. var BABYLON;
  7425. (function (BABYLON) {
  7426. var Scalar = /** @class */ (function () {
  7427. function Scalar() {
  7428. }
  7429. /**
  7430. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7431. */
  7432. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7433. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7434. var num = a - b;
  7435. return -epsilon <= num && num <= epsilon;
  7436. };
  7437. /**
  7438. * Returns a string : the upper case translation of the number i to hexadecimal.
  7439. */
  7440. Scalar.ToHex = function (i) {
  7441. var str = i.toString(16);
  7442. if (i <= 15) {
  7443. return ("0" + str).toUpperCase();
  7444. }
  7445. return str.toUpperCase();
  7446. };
  7447. /**
  7448. * Returns -1 if value is negative and +1 is value is positive.
  7449. * Returns the value itself if it's equal to zero.
  7450. */
  7451. Scalar.Sign = function (value) {
  7452. value = +value; // convert to a number
  7453. if (value === 0 || isNaN(value))
  7454. return value;
  7455. return value > 0 ? 1 : -1;
  7456. };
  7457. /**
  7458. * Returns the value itself if it's between min and max.
  7459. * Returns min if the value is lower than min.
  7460. * Returns max if the value is greater than max.
  7461. */
  7462. Scalar.Clamp = function (value, min, max) {
  7463. if (min === void 0) { min = 0; }
  7464. if (max === void 0) { max = 1; }
  7465. return Math.min(max, Math.max(min, value));
  7466. };
  7467. /**
  7468. * Returns the log2 of value.
  7469. */
  7470. Scalar.Log2 = function (value) {
  7471. return Math.log(value) * Math.LOG2E;
  7472. };
  7473. /**
  7474. * Loops the value, so that it is never larger than length and never smaller than 0.
  7475. *
  7476. * This is similar to the modulo operator but it works with floating point numbers.
  7477. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7478. * With t = 5 and length = 2.5, the result would be 0.0.
  7479. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7480. */
  7481. Scalar.Repeat = function (value, length) {
  7482. return value - Math.floor(value / length) * length;
  7483. };
  7484. /**
  7485. * Normalize the value between 0.0 and 1.0 using min and max values
  7486. */
  7487. Scalar.Normalize = function (value, min, max) {
  7488. return (value - min) / (max - min);
  7489. };
  7490. /**
  7491. * Denormalize the value from 0.0 and 1.0 using min and max values
  7492. */
  7493. Scalar.Denormalize = function (normalized, min, max) {
  7494. return (normalized * (max - min) + min);
  7495. };
  7496. /**
  7497. * Calculates the shortest difference between two given angles given in degrees.
  7498. */
  7499. Scalar.DeltaAngle = function (current, target) {
  7500. var num = Scalar.Repeat(target - current, 360.0);
  7501. if (num > 180.0) {
  7502. num -= 360.0;
  7503. }
  7504. return num;
  7505. };
  7506. /**
  7507. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7508. *
  7509. * The returned value will move back and forth between 0 and length
  7510. */
  7511. Scalar.PingPong = function (tx, length) {
  7512. var t = Scalar.Repeat(tx, length * 2.0);
  7513. return length - Math.abs(t - length);
  7514. };
  7515. /**
  7516. * Interpolates between min and max with smoothing at the limits.
  7517. *
  7518. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7519. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7520. */
  7521. Scalar.SmoothStep = function (from, to, tx) {
  7522. var t = Scalar.Clamp(tx);
  7523. t = -2.0 * t * t * t + 3.0 * t * t;
  7524. return to * t + from * (1.0 - t);
  7525. };
  7526. /**
  7527. * Moves a value current towards target.
  7528. *
  7529. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7530. * Negative values of maxDelta pushes the value away from target.
  7531. */
  7532. Scalar.MoveTowards = function (current, target, maxDelta) {
  7533. var result = 0;
  7534. if (Math.abs(target - current) <= maxDelta) {
  7535. result = target;
  7536. }
  7537. else {
  7538. result = current + Scalar.Sign(target - current) * maxDelta;
  7539. }
  7540. return result;
  7541. };
  7542. /**
  7543. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7544. *
  7545. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7546. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7547. */
  7548. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7549. var num = Scalar.DeltaAngle(current, target);
  7550. var result = 0;
  7551. if (-maxDelta < num && num < maxDelta) {
  7552. result = target;
  7553. }
  7554. else {
  7555. target = current + num;
  7556. result = Scalar.MoveTowards(current, target, maxDelta);
  7557. }
  7558. return result;
  7559. };
  7560. /**
  7561. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7562. */
  7563. Scalar.Lerp = function (start, end, amount) {
  7564. return start + ((end - start) * amount);
  7565. };
  7566. /**
  7567. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7568. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7569. */
  7570. Scalar.LerpAngle = function (start, end, amount) {
  7571. var num = Scalar.Repeat(end - start, 360.0);
  7572. if (num > 180.0) {
  7573. num -= 360.0;
  7574. }
  7575. return start + num * Scalar.Clamp(amount);
  7576. };
  7577. /**
  7578. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7579. */
  7580. Scalar.InverseLerp = function (a, b, value) {
  7581. var result = 0;
  7582. if (a != b) {
  7583. result = Scalar.Clamp((value - a) / (b - a));
  7584. }
  7585. else {
  7586. result = 0.0;
  7587. }
  7588. return result;
  7589. };
  7590. /**
  7591. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7592. */
  7593. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7594. var squared = amount * amount;
  7595. var cubed = amount * squared;
  7596. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7597. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7598. var part3 = (cubed - (2.0 * squared)) + amount;
  7599. var part4 = cubed - squared;
  7600. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7601. };
  7602. /**
  7603. * Returns a random float number between and min and max values
  7604. */
  7605. Scalar.RandomRange = function (min, max) {
  7606. if (min === max)
  7607. return min;
  7608. return ((Math.random() * (max - min)) + min);
  7609. };
  7610. /**
  7611. * This function returns percentage of a number in a given range.
  7612. *
  7613. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7614. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7615. */
  7616. Scalar.RangeToPercent = function (number, min, max) {
  7617. return ((number - min) / (max - min));
  7618. };
  7619. /**
  7620. * This function returns number that corresponds to the percentage in a given range.
  7621. *
  7622. * PercentToRange(0.34,0,100) will return 34.
  7623. */
  7624. Scalar.PercentToRange = function (percent, min, max) {
  7625. return ((max - min) * percent + min);
  7626. };
  7627. /**
  7628. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7629. * @param angle The angle to normalize in radian.
  7630. * @return The converted angle.
  7631. */
  7632. Scalar.NormalizeRadians = function (angle) {
  7633. // More precise but slower version kept for reference.
  7634. // angle = angle % Tools.TwoPi;
  7635. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7636. //if (angle > Math.PI) {
  7637. // angle -= Tools.TwoPi;
  7638. //}
  7639. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7640. return angle;
  7641. };
  7642. /**
  7643. * Two pi constants convenient for computation.
  7644. */
  7645. Scalar.TwoPi = Math.PI * 2;
  7646. return Scalar;
  7647. }());
  7648. BABYLON.Scalar = Scalar;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.math.scalar.js.map
  7651. //# sourceMappingURL=babylon.mixins.js.map
  7652. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7653. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7654. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7655. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7656. //# sourceMappingURL=babylon.webgl2.js.map
  7657. var BABYLON;
  7658. (function (BABYLON) {
  7659. var __decoratorInitialStore = {};
  7660. var __mergedStore = {};
  7661. var _copySource = function (creationFunction, source, instanciate) {
  7662. var destination = creationFunction();
  7663. // Tags
  7664. if (BABYLON.Tags) {
  7665. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7666. }
  7667. var classStore = getMergedStore(destination);
  7668. // Properties
  7669. for (var property in classStore) {
  7670. var propertyDescriptor = classStore[property];
  7671. var sourceProperty = source[property];
  7672. var propertyType = propertyDescriptor.type;
  7673. if (sourceProperty !== undefined && sourceProperty !== null) {
  7674. switch (propertyType) {
  7675. case 0: // Value
  7676. case 6: // Mesh reference
  7677. case 11: // Camera reference
  7678. destination[property] = sourceProperty;
  7679. break;
  7680. case 1: // Texture
  7681. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7682. break;
  7683. case 2: // Color3
  7684. case 3: // FresnelParameters
  7685. case 4: // Vector2
  7686. case 5: // Vector3
  7687. case 7: // Color Curves
  7688. case 10: // Quaternion
  7689. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7690. break;
  7691. }
  7692. }
  7693. }
  7694. return destination;
  7695. };
  7696. function getDirectStore(target) {
  7697. var classKey = target.getClassName();
  7698. if (!__decoratorInitialStore[classKey]) {
  7699. __decoratorInitialStore[classKey] = {};
  7700. }
  7701. return __decoratorInitialStore[classKey];
  7702. }
  7703. /**
  7704. * Return the list of properties flagged as serializable
  7705. * @param target: host object
  7706. */
  7707. function getMergedStore(target) {
  7708. var classKey = target.getClassName();
  7709. if (__mergedStore[classKey]) {
  7710. return __mergedStore[classKey];
  7711. }
  7712. __mergedStore[classKey] = {};
  7713. var store = __mergedStore[classKey];
  7714. var currentTarget = target;
  7715. var currentKey = classKey;
  7716. while (currentKey) {
  7717. var initialStore = __decoratorInitialStore[currentKey];
  7718. for (var property in initialStore) {
  7719. store[property] = initialStore[property];
  7720. }
  7721. var parent_1 = void 0;
  7722. var done = false;
  7723. do {
  7724. parent_1 = Object.getPrototypeOf(currentTarget);
  7725. if (!parent_1.getClassName) {
  7726. done = true;
  7727. break;
  7728. }
  7729. if (parent_1.getClassName() !== currentKey) {
  7730. break;
  7731. }
  7732. currentTarget = parent_1;
  7733. } while (parent_1);
  7734. if (done) {
  7735. break;
  7736. }
  7737. currentKey = parent_1.getClassName();
  7738. currentTarget = parent_1;
  7739. }
  7740. return store;
  7741. }
  7742. function generateSerializableMember(type, sourceName) {
  7743. return function (target, propertyKey) {
  7744. var classStore = getDirectStore(target);
  7745. if (!classStore[propertyKey]) {
  7746. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7747. }
  7748. };
  7749. }
  7750. function generateExpandMember(setCallback, targetKey) {
  7751. if (targetKey === void 0) { targetKey = null; }
  7752. return function (target, propertyKey) {
  7753. var key = targetKey || ("_" + propertyKey);
  7754. Object.defineProperty(target, propertyKey, {
  7755. get: function () {
  7756. return this[key];
  7757. },
  7758. set: function (value) {
  7759. if (this[key] === value) {
  7760. return;
  7761. }
  7762. this[key] = value;
  7763. target[setCallback].apply(this);
  7764. },
  7765. enumerable: true,
  7766. configurable: true
  7767. });
  7768. };
  7769. }
  7770. function expandToProperty(callback, targetKey) {
  7771. if (targetKey === void 0) { targetKey = null; }
  7772. return generateExpandMember(callback, targetKey);
  7773. }
  7774. BABYLON.expandToProperty = expandToProperty;
  7775. function serialize(sourceName) {
  7776. return generateSerializableMember(0, sourceName); // value member
  7777. }
  7778. BABYLON.serialize = serialize;
  7779. function serializeAsTexture(sourceName) {
  7780. return generateSerializableMember(1, sourceName); // texture member
  7781. }
  7782. BABYLON.serializeAsTexture = serializeAsTexture;
  7783. function serializeAsColor3(sourceName) {
  7784. return generateSerializableMember(2, sourceName); // color3 member
  7785. }
  7786. BABYLON.serializeAsColor3 = serializeAsColor3;
  7787. function serializeAsFresnelParameters(sourceName) {
  7788. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7789. }
  7790. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7791. function serializeAsVector2(sourceName) {
  7792. return generateSerializableMember(4, sourceName); // vector2 member
  7793. }
  7794. BABYLON.serializeAsVector2 = serializeAsVector2;
  7795. function serializeAsVector3(sourceName) {
  7796. return generateSerializableMember(5, sourceName); // vector3 member
  7797. }
  7798. BABYLON.serializeAsVector3 = serializeAsVector3;
  7799. function serializeAsMeshReference(sourceName) {
  7800. return generateSerializableMember(6, sourceName); // mesh reference member
  7801. }
  7802. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7803. function serializeAsColorCurves(sourceName) {
  7804. return generateSerializableMember(7, sourceName); // color curves
  7805. }
  7806. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7807. function serializeAsColor4(sourceName) {
  7808. return generateSerializableMember(8, sourceName); // color 4
  7809. }
  7810. BABYLON.serializeAsColor4 = serializeAsColor4;
  7811. function serializeAsImageProcessingConfiguration(sourceName) {
  7812. return generateSerializableMember(9, sourceName); // image processing
  7813. }
  7814. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7815. function serializeAsQuaternion(sourceName) {
  7816. return generateSerializableMember(10, sourceName); // quaternion member
  7817. }
  7818. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7819. /**
  7820. * Decorator used to define property that can be serialized as reference to a camera
  7821. * @param sourceName defines the name of the property to decorate
  7822. */
  7823. function serializeAsCameraReference(sourceName) {
  7824. return generateSerializableMember(11, sourceName); // camera reference member
  7825. }
  7826. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7827. var SerializationHelper = /** @class */ (function () {
  7828. function SerializationHelper() {
  7829. }
  7830. SerializationHelper.Serialize = function (entity, serializationObject) {
  7831. if (!serializationObject) {
  7832. serializationObject = {};
  7833. }
  7834. // Tags
  7835. if (BABYLON.Tags) {
  7836. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7837. }
  7838. var serializedProperties = getMergedStore(entity);
  7839. // Properties
  7840. for (var property in serializedProperties) {
  7841. var propertyDescriptor = serializedProperties[property];
  7842. var targetPropertyName = propertyDescriptor.sourceName || property;
  7843. var propertyType = propertyDescriptor.type;
  7844. var sourceProperty = entity[property];
  7845. if (sourceProperty !== undefined && sourceProperty !== null) {
  7846. switch (propertyType) {
  7847. case 0: // Value
  7848. serializationObject[targetPropertyName] = sourceProperty;
  7849. break;
  7850. case 1: // Texture
  7851. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7852. break;
  7853. case 2: // Color3
  7854. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7855. break;
  7856. case 3: // FresnelParameters
  7857. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7858. break;
  7859. case 4: // Vector2
  7860. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7861. break;
  7862. case 5: // Vector3
  7863. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7864. break;
  7865. case 6: // Mesh reference
  7866. serializationObject[targetPropertyName] = sourceProperty.id;
  7867. break;
  7868. case 7: // Color Curves
  7869. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7870. break;
  7871. case 8: // Color 4
  7872. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7873. break;
  7874. case 9: // Image Processing
  7875. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7876. break;
  7877. case 10: // Quaternion
  7878. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7879. break;
  7880. case 11: // Camera reference
  7881. serializationObject[targetPropertyName] = sourceProperty.id;
  7882. break;
  7883. }
  7884. }
  7885. }
  7886. return serializationObject;
  7887. };
  7888. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7889. if (rootUrl === void 0) { rootUrl = null; }
  7890. var destination = creationFunction();
  7891. if (!rootUrl) {
  7892. rootUrl = "";
  7893. }
  7894. // Tags
  7895. if (BABYLON.Tags) {
  7896. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7897. }
  7898. var classStore = getMergedStore(destination);
  7899. // Properties
  7900. for (var property in classStore) {
  7901. var propertyDescriptor = classStore[property];
  7902. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7903. var propertyType = propertyDescriptor.type;
  7904. if (sourceProperty !== undefined && sourceProperty !== null) {
  7905. var dest = destination;
  7906. switch (propertyType) {
  7907. case 0: // Value
  7908. dest[property] = sourceProperty;
  7909. break;
  7910. case 1: // Texture
  7911. if (scene) {
  7912. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7913. }
  7914. break;
  7915. case 2: // Color3
  7916. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7917. break;
  7918. case 3: // FresnelParameters
  7919. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7920. break;
  7921. case 4: // Vector2
  7922. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7923. break;
  7924. case 5: // Vector3
  7925. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7926. break;
  7927. case 6: // Mesh reference
  7928. if (scene) {
  7929. dest[property] = scene.getLastMeshByID(sourceProperty);
  7930. }
  7931. break;
  7932. case 7: // Color Curves
  7933. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7934. break;
  7935. case 8: // Color 4
  7936. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7937. break;
  7938. case 9: // Image Processing
  7939. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7940. break;
  7941. case 10: // Quaternion
  7942. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7943. break;
  7944. case 11: // Camera reference
  7945. if (scene) {
  7946. dest[property] = scene.getCameraByID(sourceProperty);
  7947. }
  7948. break;
  7949. }
  7950. }
  7951. }
  7952. return destination;
  7953. };
  7954. SerializationHelper.Clone = function (creationFunction, source) {
  7955. return _copySource(creationFunction, source, false);
  7956. };
  7957. SerializationHelper.Instanciate = function (creationFunction, source) {
  7958. return _copySource(creationFunction, source, true);
  7959. };
  7960. return SerializationHelper;
  7961. }());
  7962. BABYLON.SerializationHelper = SerializationHelper;
  7963. })(BABYLON || (BABYLON = {}));
  7964. //# sourceMappingURL=babylon.decorators.js.map
  7965. var BABYLON;
  7966. (function (BABYLON) {
  7967. /**
  7968. * Wrapper class for promise with external resolve and reject.
  7969. */
  7970. var Deferred = /** @class */ (function () {
  7971. /**
  7972. * Constructor for this deferred object.
  7973. */
  7974. function Deferred() {
  7975. var _this = this;
  7976. this.promise = new Promise(function (resolve, reject) {
  7977. _this._resolve = resolve;
  7978. _this._reject = reject;
  7979. });
  7980. }
  7981. Object.defineProperty(Deferred.prototype, "resolve", {
  7982. /**
  7983. * The resolve method of the promise associated with this deferred object.
  7984. */
  7985. get: function () {
  7986. return this._resolve;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Deferred.prototype, "reject", {
  7992. /**
  7993. * The reject method of the promise associated with this deferred object.
  7994. */
  7995. get: function () {
  7996. return this._reject;
  7997. },
  7998. enumerable: true,
  7999. configurable: true
  8000. });
  8001. return Deferred;
  8002. }());
  8003. BABYLON.Deferred = Deferred;
  8004. })(BABYLON || (BABYLON = {}));
  8005. //# sourceMappingURL=babylon.deferred.js.map
  8006. var BABYLON;
  8007. (function (BABYLON) {
  8008. /**
  8009. * A class serves as a medium between the observable and its observers
  8010. */
  8011. var EventState = /** @class */ (function () {
  8012. /**
  8013. * Create a new EventState
  8014. * @param mask defines the mask associated with this state
  8015. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8016. * @param target defines the original target of the state
  8017. * @param currentTarget defines the current target of the state
  8018. */
  8019. function EventState(mask, skipNextObservers, target, currentTarget) {
  8020. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8021. this.initalize(mask, skipNextObservers, target, currentTarget);
  8022. }
  8023. /**
  8024. * Initialize the current event state
  8025. * @param mask defines the mask associated with this state
  8026. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8027. * @param target defines the original target of the state
  8028. * @param currentTarget defines the current target of the state
  8029. * @returns the current event state
  8030. */
  8031. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8032. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8033. this.mask = mask;
  8034. this.skipNextObservers = skipNextObservers;
  8035. this.target = target;
  8036. this.currentTarget = currentTarget;
  8037. return this;
  8038. };
  8039. return EventState;
  8040. }());
  8041. BABYLON.EventState = EventState;
  8042. /**
  8043. * Represent an Observer registered to a given Observable object.
  8044. */
  8045. var Observer = /** @class */ (function () {
  8046. /**
  8047. * Creates a new observer
  8048. * @param callback defines the callback to call when the observer is notified
  8049. * @param mask defines the mask of the observer (used to filter notifications)
  8050. * @param scope defines the current scope used to restore the JS context
  8051. */
  8052. function Observer(
  8053. /**
  8054. * Defines the callback to call when the observer is notified
  8055. */
  8056. callback,
  8057. /**
  8058. * Defines the mask of the observer (used to filter notifications)
  8059. */
  8060. mask,
  8061. /**
  8062. * Defines the current scope used to restore the JS context
  8063. */
  8064. scope) {
  8065. if (scope === void 0) { scope = null; }
  8066. this.callback = callback;
  8067. this.mask = mask;
  8068. this.scope = scope;
  8069. /** @hidden */
  8070. this._willBeUnregistered = false;
  8071. /**
  8072. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8073. */
  8074. this.unregisterOnNextCall = false;
  8075. }
  8076. return Observer;
  8077. }());
  8078. BABYLON.Observer = Observer;
  8079. /**
  8080. * Represent a list of observers registered to multiple Observables object.
  8081. */
  8082. var MultiObserver = /** @class */ (function () {
  8083. function MultiObserver() {
  8084. }
  8085. /**
  8086. * Release associated resources
  8087. */
  8088. MultiObserver.prototype.dispose = function () {
  8089. if (this._observers && this._observables) {
  8090. for (var index = 0; index < this._observers.length; index++) {
  8091. this._observables[index].remove(this._observers[index]);
  8092. }
  8093. }
  8094. this._observers = null;
  8095. this._observables = null;
  8096. };
  8097. /**
  8098. * Raise a callback when one of the observable will notify
  8099. * @param observables defines a list of observables to watch
  8100. * @param callback defines the callback to call on notification
  8101. * @param mask defines the mask used to filter notifications
  8102. * @param scope defines the current scope used to restore the JS context
  8103. * @returns the new MultiObserver
  8104. */
  8105. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8106. if (mask === void 0) { mask = -1; }
  8107. if (scope === void 0) { scope = null; }
  8108. var result = new MultiObserver();
  8109. result._observers = new Array();
  8110. result._observables = observables;
  8111. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8112. var observable = observables_1[_i];
  8113. var observer = observable.add(callback, mask, false, scope);
  8114. if (observer) {
  8115. result._observers.push(observer);
  8116. }
  8117. }
  8118. return result;
  8119. };
  8120. return MultiObserver;
  8121. }());
  8122. BABYLON.MultiObserver = MultiObserver;
  8123. /**
  8124. * The Observable class is a simple implementation of the Observable pattern.
  8125. *
  8126. * 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.
  8127. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8128. * 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).
  8129. * 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.
  8130. */
  8131. var Observable = /** @class */ (function () {
  8132. /**
  8133. * Creates a new observable
  8134. * @param onObserverAdded defines a callback to call when a new observer is added
  8135. */
  8136. function Observable(onObserverAdded) {
  8137. this._observers = new Array();
  8138. this._eventState = new EventState(0);
  8139. if (onObserverAdded) {
  8140. this._onObserverAdded = onObserverAdded;
  8141. }
  8142. }
  8143. /**
  8144. * Create a new Observer with the specified callback
  8145. * @param callback the callback that will be executed for that Observer
  8146. * @param mask the mask used to filter observers
  8147. * @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.
  8148. * @param scope optional scope for the callback to be called from
  8149. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8150. * @returns the new observer created for the callback
  8151. */
  8152. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8153. if (mask === void 0) { mask = -1; }
  8154. if (insertFirst === void 0) { insertFirst = false; }
  8155. if (scope === void 0) { scope = null; }
  8156. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8157. if (!callback) {
  8158. return null;
  8159. }
  8160. var observer = new Observer(callback, mask, scope);
  8161. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8162. if (insertFirst) {
  8163. this._observers.unshift(observer);
  8164. }
  8165. else {
  8166. this._observers.push(observer);
  8167. }
  8168. if (this._onObserverAdded) {
  8169. this._onObserverAdded(observer);
  8170. }
  8171. return observer;
  8172. };
  8173. /**
  8174. * Create a new Observer with the specified callback and unregisters after the next notification
  8175. * @param callback the callback that will be executed for that Observer
  8176. * @returns the new observer created for the callback
  8177. */
  8178. Observable.prototype.addOnce = function (callback) {
  8179. return this.add(callback, undefined, undefined, undefined, true);
  8180. };
  8181. /**
  8182. * Remove an Observer from the Observable object
  8183. * @param observer the instance of the Observer to remove
  8184. * @returns false if it doesn't belong to this Observable
  8185. */
  8186. Observable.prototype.remove = function (observer) {
  8187. if (!observer) {
  8188. return false;
  8189. }
  8190. var index = this._observers.indexOf(observer);
  8191. if (index !== -1) {
  8192. this._observers.splice(index, 1);
  8193. return true;
  8194. }
  8195. return false;
  8196. };
  8197. /**
  8198. * Remove a callback from the Observable object
  8199. * @param callback the callback to remove
  8200. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8201. * @returns false if it doesn't belong to this Observable
  8202. */
  8203. Observable.prototype.removeCallback = function (callback, scope) {
  8204. for (var index = 0; index < this._observers.length; index++) {
  8205. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8206. this._observers.splice(index, 1);
  8207. return true;
  8208. }
  8209. }
  8210. return false;
  8211. };
  8212. Observable.prototype._deferUnregister = function (observer) {
  8213. var _this = this;
  8214. observer.unregisterOnNextCall = false;
  8215. observer._willBeUnregistered = true;
  8216. BABYLON.Tools.SetImmediate(function () {
  8217. _this.remove(observer);
  8218. });
  8219. };
  8220. /**
  8221. * Notify all Observers by calling their respective callback with the given data
  8222. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8223. * @param eventData defines the data to send to all observers
  8224. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8225. * @param target defines the original target of the state
  8226. * @param currentTarget defines the current target of the state
  8227. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8228. */
  8229. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8230. if (mask === void 0) { mask = -1; }
  8231. if (!this._observers.length) {
  8232. return true;
  8233. }
  8234. var state = this._eventState;
  8235. state.mask = mask;
  8236. state.target = target;
  8237. state.currentTarget = currentTarget;
  8238. state.skipNextObservers = false;
  8239. state.lastReturnValue = eventData;
  8240. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8241. var obs = _a[_i];
  8242. if (obs._willBeUnregistered) {
  8243. continue;
  8244. }
  8245. if (obs.mask & mask) {
  8246. if (obs.scope) {
  8247. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8248. }
  8249. else {
  8250. state.lastReturnValue = obs.callback(eventData, state);
  8251. }
  8252. if (obs.unregisterOnNextCall) {
  8253. this._deferUnregister(obs);
  8254. }
  8255. }
  8256. if (state.skipNextObservers) {
  8257. return false;
  8258. }
  8259. }
  8260. return true;
  8261. };
  8262. /**
  8263. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8264. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8265. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8266. * and it is crucial that all callbacks will be executed.
  8267. * The order of the callbacks is kept, callbacks are not executed parallel.
  8268. *
  8269. * @param eventData The data to be sent to each callback
  8270. * @param mask is used to filter observers defaults to -1
  8271. * @param target defines the callback target (see EventState)
  8272. * @param currentTarget defines he current object in the bubbling phase
  8273. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8274. */
  8275. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8276. var _this = this;
  8277. if (mask === void 0) { mask = -1; }
  8278. // create an empty promise
  8279. var p = Promise.resolve(eventData);
  8280. // no observers? return this promise.
  8281. if (!this._observers.length) {
  8282. return p;
  8283. }
  8284. var state = this._eventState;
  8285. state.mask = mask;
  8286. state.target = target;
  8287. state.currentTarget = currentTarget;
  8288. state.skipNextObservers = false;
  8289. // execute one callback after another (not using Promise.all, the order is important)
  8290. this._observers.forEach(function (obs) {
  8291. if (state.skipNextObservers) {
  8292. return;
  8293. }
  8294. if (obs._willBeUnregistered) {
  8295. return;
  8296. }
  8297. if (obs.mask & mask) {
  8298. if (obs.scope) {
  8299. p = p.then(function (lastReturnedValue) {
  8300. state.lastReturnValue = lastReturnedValue;
  8301. return obs.callback.apply(obs.scope, [eventData, state]);
  8302. });
  8303. }
  8304. else {
  8305. p = p.then(function (lastReturnedValue) {
  8306. state.lastReturnValue = lastReturnedValue;
  8307. return obs.callback(eventData, state);
  8308. });
  8309. }
  8310. if (obs.unregisterOnNextCall) {
  8311. _this._deferUnregister(obs);
  8312. }
  8313. }
  8314. });
  8315. // return the eventData
  8316. return p.then(function () { return eventData; });
  8317. };
  8318. /**
  8319. * Notify a specific observer
  8320. * @param observer defines the observer to notify
  8321. * @param eventData defines the data to be sent to each callback
  8322. * @param mask is used to filter observers defaults to -1
  8323. */
  8324. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8325. if (mask === void 0) { mask = -1; }
  8326. var state = this._eventState;
  8327. state.mask = mask;
  8328. state.skipNextObservers = false;
  8329. observer.callback(eventData, state);
  8330. };
  8331. /**
  8332. * Gets a boolean indicating if the observable has at least one observer
  8333. * @returns true is the Observable has at least one Observer registered
  8334. */
  8335. Observable.prototype.hasObservers = function () {
  8336. return this._observers.length > 0;
  8337. };
  8338. /**
  8339. * Clear the list of observers
  8340. */
  8341. Observable.prototype.clear = function () {
  8342. this._observers = new Array();
  8343. this._onObserverAdded = null;
  8344. };
  8345. /**
  8346. * Clone the current observable
  8347. * @returns a new observable
  8348. */
  8349. Observable.prototype.clone = function () {
  8350. var result = new Observable();
  8351. result._observers = this._observers.slice(0);
  8352. return result;
  8353. };
  8354. /**
  8355. * Does this observable handles observer registered with a given mask
  8356. * @param mask defines the mask to be tested
  8357. * @return whether or not one observer registered with the given mask is handeled
  8358. **/
  8359. Observable.prototype.hasSpecificMask = function (mask) {
  8360. if (mask === void 0) { mask = -1; }
  8361. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8362. var obs = _a[_i];
  8363. if (obs.mask & mask || obs.mask === mask) {
  8364. return true;
  8365. }
  8366. }
  8367. return false;
  8368. };
  8369. return Observable;
  8370. }());
  8371. BABYLON.Observable = Observable;
  8372. })(BABYLON || (BABYLON = {}));
  8373. //# sourceMappingURL=babylon.observable.js.map
  8374. var BABYLON;
  8375. (function (BABYLON) {
  8376. var SmartArray = /** @class */ (function () {
  8377. function SmartArray(capacity) {
  8378. this.length = 0;
  8379. this.data = new Array(capacity);
  8380. this._id = SmartArray._GlobalId++;
  8381. }
  8382. SmartArray.prototype.push = function (value) {
  8383. this.data[this.length++] = value;
  8384. if (this.length > this.data.length) {
  8385. this.data.length *= 2;
  8386. }
  8387. };
  8388. SmartArray.prototype.forEach = function (func) {
  8389. for (var index = 0; index < this.length; index++) {
  8390. func(this.data[index]);
  8391. }
  8392. };
  8393. SmartArray.prototype.sort = function (compareFn) {
  8394. this.data.sort(compareFn);
  8395. };
  8396. SmartArray.prototype.reset = function () {
  8397. this.length = 0;
  8398. };
  8399. SmartArray.prototype.dispose = function () {
  8400. this.reset();
  8401. if (this.data) {
  8402. this.data.length = 0;
  8403. this.data = [];
  8404. }
  8405. };
  8406. SmartArray.prototype.concat = function (array) {
  8407. if (array.length === 0) {
  8408. return;
  8409. }
  8410. if (this.length + array.length > this.data.length) {
  8411. this.data.length = (this.length + array.length) * 2;
  8412. }
  8413. for (var index = 0; index < array.length; index++) {
  8414. this.data[this.length++] = (array.data || array)[index];
  8415. }
  8416. };
  8417. SmartArray.prototype.indexOf = function (value) {
  8418. var position = this.data.indexOf(value);
  8419. if (position >= this.length) {
  8420. return -1;
  8421. }
  8422. return position;
  8423. };
  8424. SmartArray.prototype.contains = function (value) {
  8425. return this.data.indexOf(value) !== -1;
  8426. };
  8427. // Statics
  8428. SmartArray._GlobalId = 0;
  8429. return SmartArray;
  8430. }());
  8431. BABYLON.SmartArray = SmartArray;
  8432. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8433. __extends(SmartArrayNoDuplicate, _super);
  8434. function SmartArrayNoDuplicate() {
  8435. var _this = _super !== null && _super.apply(this, arguments) || this;
  8436. _this._duplicateId = 0;
  8437. return _this;
  8438. }
  8439. SmartArrayNoDuplicate.prototype.push = function (value) {
  8440. _super.prototype.push.call(this, value);
  8441. if (!value.__smartArrayFlags) {
  8442. value.__smartArrayFlags = {};
  8443. }
  8444. value.__smartArrayFlags[this._id] = this._duplicateId;
  8445. };
  8446. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8447. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8448. return false;
  8449. }
  8450. this.push(value);
  8451. return true;
  8452. };
  8453. SmartArrayNoDuplicate.prototype.reset = function () {
  8454. _super.prototype.reset.call(this);
  8455. this._duplicateId++;
  8456. };
  8457. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8458. if (array.length === 0) {
  8459. return;
  8460. }
  8461. if (this.length + array.length > this.data.length) {
  8462. this.data.length = (this.length + array.length) * 2;
  8463. }
  8464. for (var index = 0; index < array.length; index++) {
  8465. var item = (array.data || array)[index];
  8466. this.pushNoDuplicate(item);
  8467. }
  8468. };
  8469. return SmartArrayNoDuplicate;
  8470. }(SmartArray));
  8471. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8472. })(BABYLON || (BABYLON = {}));
  8473. //# sourceMappingURL=babylon.smartArray.js.map
  8474. var BABYLON;
  8475. (function (BABYLON) {
  8476. /** Class used to store color gradient */
  8477. var ColorGradient = /** @class */ (function () {
  8478. function ColorGradient() {
  8479. }
  8480. return ColorGradient;
  8481. }());
  8482. BABYLON.ColorGradient = ColorGradient;
  8483. /** Class used to store factor gradient */
  8484. var FactorGradient = /** @class */ (function () {
  8485. function FactorGradient() {
  8486. }
  8487. return FactorGradient;
  8488. }());
  8489. BABYLON.FactorGradient = FactorGradient;
  8490. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8491. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8492. var LoadFileError = /** @class */ (function (_super) {
  8493. __extends(LoadFileError, _super);
  8494. function LoadFileError(message, request) {
  8495. var _this = _super.call(this, message) || this;
  8496. _this.request = request;
  8497. _this.name = "LoadFileError";
  8498. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8499. return _this;
  8500. }
  8501. // Polyfill for Object.setPrototypeOf if necessary.
  8502. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8503. return LoadFileError;
  8504. }(Error));
  8505. BABYLON.LoadFileError = LoadFileError;
  8506. var RetryStrategy = /** @class */ (function () {
  8507. function RetryStrategy() {
  8508. }
  8509. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8510. if (maxRetries === void 0) { maxRetries = 3; }
  8511. if (baseInterval === void 0) { baseInterval = 500; }
  8512. return function (url, request, retryIndex) {
  8513. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8514. return -1;
  8515. }
  8516. return Math.pow(2, retryIndex) * baseInterval;
  8517. };
  8518. };
  8519. return RetryStrategy;
  8520. }());
  8521. BABYLON.RetryStrategy = RetryStrategy;
  8522. // Screenshots
  8523. var screenshotCanvas;
  8524. var cloneValue = function (source, destinationObject) {
  8525. if (!source)
  8526. return null;
  8527. if (source instanceof BABYLON.Mesh) {
  8528. return null;
  8529. }
  8530. if (source instanceof BABYLON.SubMesh) {
  8531. return source.clone(destinationObject);
  8532. }
  8533. else if (source.clone) {
  8534. return source.clone();
  8535. }
  8536. return null;
  8537. };
  8538. var Tools = /** @class */ (function () {
  8539. function Tools() {
  8540. }
  8541. /**
  8542. * Interpolates between a and b via alpha
  8543. * @param a The lower value (returned when alpha = 0)
  8544. * @param b The upper value (returned when alpha = 1)
  8545. * @param alpha The interpolation-factor
  8546. * @return The mixed value
  8547. */
  8548. Tools.Mix = function (a, b, alpha) {
  8549. return a * (1 - alpha) + b * alpha;
  8550. };
  8551. Tools.Instantiate = function (className) {
  8552. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8553. return Tools.RegisteredExternalClasses[className];
  8554. }
  8555. var arr = className.split(".");
  8556. var fn = (window || this);
  8557. for (var i = 0, len = arr.length; i < len; i++) {
  8558. fn = fn[arr[i]];
  8559. }
  8560. if (typeof fn !== "function") {
  8561. return null;
  8562. }
  8563. return fn;
  8564. };
  8565. /**
  8566. * Provides a slice function that will work even on IE
  8567. * @param data defines the array to slice
  8568. * @param start defines the start of the data (optional)
  8569. * @param end defines the end of the data (optional)
  8570. * @returns the new sliced array
  8571. */
  8572. Tools.Slice = function (data, start, end) {
  8573. if (data.slice) {
  8574. return data.slice(start, end);
  8575. }
  8576. return Array.prototype.slice.call(data, start, end);
  8577. };
  8578. Tools.SetImmediate = function (action) {
  8579. if (window.setImmediate) {
  8580. window.setImmediate(action);
  8581. }
  8582. else {
  8583. setTimeout(action, 1);
  8584. }
  8585. };
  8586. Tools.IsExponentOfTwo = function (value) {
  8587. var count = 1;
  8588. do {
  8589. count *= 2;
  8590. } while (count < value);
  8591. return count === value;
  8592. };
  8593. /**
  8594. * Returns the nearest 32-bit single precision float representation of a Number
  8595. * @param value A Number. If the parameter is of a different type, it will get converted
  8596. * to a number or to NaN if it cannot be converted
  8597. * @returns number
  8598. */
  8599. Tools.FloatRound = function (value) {
  8600. if (Math.fround) {
  8601. return Math.fround(value);
  8602. }
  8603. return (Tools._tmpFloatArray[0] = value);
  8604. };
  8605. /**
  8606. * Find the next highest power of two.
  8607. * @param x Number to start search from.
  8608. * @return Next highest power of two.
  8609. */
  8610. Tools.CeilingPOT = function (x) {
  8611. x--;
  8612. x |= x >> 1;
  8613. x |= x >> 2;
  8614. x |= x >> 4;
  8615. x |= x >> 8;
  8616. x |= x >> 16;
  8617. x++;
  8618. return x;
  8619. };
  8620. /**
  8621. * Find the next lowest power of two.
  8622. * @param x Number to start search from.
  8623. * @return Next lowest power of two.
  8624. */
  8625. Tools.FloorPOT = function (x) {
  8626. x = x | (x >> 1);
  8627. x = x | (x >> 2);
  8628. x = x | (x >> 4);
  8629. x = x | (x >> 8);
  8630. x = x | (x >> 16);
  8631. return x - (x >> 1);
  8632. };
  8633. /**
  8634. * Find the nearest power of two.
  8635. * @param x Number to start search from.
  8636. * @return Next nearest power of two.
  8637. */
  8638. Tools.NearestPOT = function (x) {
  8639. var c = Tools.CeilingPOT(x);
  8640. var f = Tools.FloorPOT(x);
  8641. return (c - x) > (x - f) ? f : c;
  8642. };
  8643. Tools.GetExponentOfTwo = function (value, max, mode) {
  8644. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8645. var pot;
  8646. switch (mode) {
  8647. case BABYLON.Engine.SCALEMODE_FLOOR:
  8648. pot = Tools.FloorPOT(value);
  8649. break;
  8650. case BABYLON.Engine.SCALEMODE_NEAREST:
  8651. pot = Tools.NearestPOT(value);
  8652. break;
  8653. case BABYLON.Engine.SCALEMODE_CEILING:
  8654. default:
  8655. pot = Tools.CeilingPOT(value);
  8656. break;
  8657. }
  8658. return Math.min(pot, max);
  8659. };
  8660. Tools.GetFilename = function (path) {
  8661. var index = path.lastIndexOf("/");
  8662. if (index < 0)
  8663. return path;
  8664. return path.substring(index + 1);
  8665. };
  8666. /**
  8667. * Extracts the "folder" part of a path (everything before the filename).
  8668. * @param uri The URI to extract the info from
  8669. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8670. * @returns The "folder" part of the path
  8671. */
  8672. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8673. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8674. var index = uri.lastIndexOf("/");
  8675. if (index < 0) {
  8676. if (returnUnchangedIfNoSlash) {
  8677. return uri;
  8678. }
  8679. return "";
  8680. }
  8681. return uri.substring(0, index + 1);
  8682. };
  8683. Tools.GetDOMTextContent = function (element) {
  8684. var result = "";
  8685. var child = element.firstChild;
  8686. while (child) {
  8687. if (child.nodeType === 3) {
  8688. result += child.textContent;
  8689. }
  8690. child = child.nextSibling;
  8691. }
  8692. return result;
  8693. };
  8694. Tools.ToDegrees = function (angle) {
  8695. return angle * 180 / Math.PI;
  8696. };
  8697. Tools.ToRadians = function (angle) {
  8698. return angle * Math.PI / 180;
  8699. };
  8700. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8701. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8702. var output = "";
  8703. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8704. var i = 0;
  8705. var bytes = new Uint8Array(buffer);
  8706. while (i < bytes.length) {
  8707. chr1 = bytes[i++];
  8708. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8709. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8710. enc1 = chr1 >> 2;
  8711. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8712. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8713. enc4 = chr3 & 63;
  8714. if (isNaN(chr2)) {
  8715. enc3 = enc4 = 64;
  8716. }
  8717. else if (isNaN(chr3)) {
  8718. enc4 = 64;
  8719. }
  8720. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8721. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8722. }
  8723. return "data:image/png;base64," + output;
  8724. };
  8725. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8726. if (bias === void 0) { bias = null; }
  8727. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8728. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8729. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8730. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8731. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8732. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8733. }
  8734. if (bias) {
  8735. minimum.x -= minimum.x * bias.x + bias.y;
  8736. minimum.y -= minimum.y * bias.x + bias.y;
  8737. minimum.z -= minimum.z * bias.x + bias.y;
  8738. maximum.x += maximum.x * bias.x + bias.y;
  8739. maximum.y += maximum.y * bias.x + bias.y;
  8740. maximum.z += maximum.z * bias.x + bias.y;
  8741. }
  8742. return {
  8743. minimum: minimum,
  8744. maximum: maximum
  8745. };
  8746. };
  8747. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8748. if (bias === void 0) { bias = null; }
  8749. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8750. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8751. if (!stride) {
  8752. stride = 3;
  8753. }
  8754. for (var index = start; index < start + count; index++) {
  8755. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8756. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8757. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8758. }
  8759. if (bias) {
  8760. minimum.x -= minimum.x * bias.x + bias.y;
  8761. minimum.y -= minimum.y * bias.x + bias.y;
  8762. minimum.z -= minimum.z * bias.x + bias.y;
  8763. maximum.x += maximum.x * bias.x + bias.y;
  8764. maximum.y += maximum.y * bias.x + bias.y;
  8765. maximum.z += maximum.z * bias.x + bias.y;
  8766. }
  8767. return {
  8768. minimum: minimum,
  8769. maximum: maximum
  8770. };
  8771. };
  8772. Tools.Vector2ArrayFeeder = function (array) {
  8773. return function (index) {
  8774. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8775. var length = isFloatArray ? array.length / 2 : array.length;
  8776. if (index >= length) {
  8777. return null;
  8778. }
  8779. if (isFloatArray) {
  8780. var fa = array;
  8781. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8782. }
  8783. var a = array;
  8784. return a[index];
  8785. };
  8786. };
  8787. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8788. if (bias === void 0) { bias = null; }
  8789. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8790. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8791. var i = 0;
  8792. var cur = feeder(i++);
  8793. while (cur) {
  8794. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8795. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8796. cur = feeder(i++);
  8797. }
  8798. if (bias) {
  8799. minimum.x -= minimum.x * bias.x + bias.y;
  8800. minimum.y -= minimum.y * bias.x + bias.y;
  8801. maximum.x += maximum.x * bias.x + bias.y;
  8802. maximum.y += maximum.y * bias.x + bias.y;
  8803. }
  8804. return {
  8805. minimum: minimum,
  8806. maximum: maximum
  8807. };
  8808. };
  8809. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8810. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8811. return null;
  8812. return Array.isArray(obj) ? obj : [obj];
  8813. };
  8814. // Misc.
  8815. Tools.GetPointerPrefix = function () {
  8816. var eventPrefix = "pointer";
  8817. // Check if pointer events are supported
  8818. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8819. eventPrefix = "mouse";
  8820. }
  8821. return eventPrefix;
  8822. };
  8823. /**
  8824. * @param func - the function to be called
  8825. * @param requester - the object that will request the next frame. Falls back to window.
  8826. */
  8827. Tools.QueueNewFrame = function (func, requester) {
  8828. if (!Tools.IsWindowObjectExist()) {
  8829. return setTimeout(func, 16);
  8830. }
  8831. if (!requester) {
  8832. requester = window;
  8833. }
  8834. if (requester.requestAnimationFrame) {
  8835. return requester.requestAnimationFrame(func);
  8836. }
  8837. else if (requester.msRequestAnimationFrame) {
  8838. return requester.msRequestAnimationFrame(func);
  8839. }
  8840. else if (requester.webkitRequestAnimationFrame) {
  8841. return requester.webkitRequestAnimationFrame(func);
  8842. }
  8843. else if (requester.mozRequestAnimationFrame) {
  8844. return requester.mozRequestAnimationFrame(func);
  8845. }
  8846. else if (requester.oRequestAnimationFrame) {
  8847. return requester.oRequestAnimationFrame(func);
  8848. }
  8849. else {
  8850. return window.setTimeout(func, 16);
  8851. }
  8852. };
  8853. Tools.RequestFullscreen = function (element) {
  8854. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8855. if (!requestFunction)
  8856. return;
  8857. requestFunction.call(element);
  8858. };
  8859. Tools.ExitFullscreen = function () {
  8860. if (document.exitFullscreen) {
  8861. document.exitFullscreen();
  8862. }
  8863. else if (document.mozCancelFullScreen) {
  8864. document.mozCancelFullScreen();
  8865. }
  8866. else if (document.webkitCancelFullScreen) {
  8867. document.webkitCancelFullScreen();
  8868. }
  8869. else if (document.msCancelFullScreen) {
  8870. document.msCancelFullScreen();
  8871. }
  8872. };
  8873. Tools.SetCorsBehavior = function (url, element) {
  8874. if (url && url.indexOf("data:") === 0) {
  8875. return;
  8876. }
  8877. if (Tools.CorsBehavior) {
  8878. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8879. element.crossOrigin = Tools.CorsBehavior;
  8880. }
  8881. else {
  8882. var result = Tools.CorsBehavior(url);
  8883. if (result) {
  8884. element.crossOrigin = result;
  8885. }
  8886. }
  8887. }
  8888. };
  8889. // External files
  8890. Tools.CleanUrl = function (url) {
  8891. url = url.replace(/#/mg, "%23");
  8892. return url;
  8893. };
  8894. /**
  8895. * Loads an image as an HTMLImageElement.
  8896. * @param input url string, ArrayBuffer, or Blob to load
  8897. * @param onLoad callback called when the image successfully loads
  8898. * @param onError callback called when the image fails to load
  8899. * @param database database for caching
  8900. * @returns the HTMLImageElement of the loaded image
  8901. */
  8902. Tools.LoadImage = function (input, onLoad, onError, database) {
  8903. var url;
  8904. var usingObjectURL = false;
  8905. if (input instanceof ArrayBuffer) {
  8906. url = URL.createObjectURL(new Blob([input]));
  8907. usingObjectURL = true;
  8908. }
  8909. else if (input instanceof Blob) {
  8910. url = URL.createObjectURL(input);
  8911. usingObjectURL = true;
  8912. }
  8913. else {
  8914. url = Tools.CleanUrl(input);
  8915. url = Tools.PreprocessUrl(input);
  8916. }
  8917. var img = new Image();
  8918. Tools.SetCorsBehavior(url, img);
  8919. var loadHandler = function () {
  8920. if (usingObjectURL && img.src) {
  8921. URL.revokeObjectURL(img.src);
  8922. }
  8923. img.removeEventListener("load", loadHandler);
  8924. img.removeEventListener("error", errorHandler);
  8925. onLoad(img);
  8926. };
  8927. var errorHandler = function (err) {
  8928. if (usingObjectURL && img.src) {
  8929. URL.revokeObjectURL(img.src);
  8930. }
  8931. img.removeEventListener("load", loadHandler);
  8932. img.removeEventListener("error", errorHandler);
  8933. Tools.Error("Error while trying to load image: " + input);
  8934. if (onError) {
  8935. onError("Error while trying to load image: " + input, err);
  8936. }
  8937. };
  8938. img.addEventListener("load", loadHandler);
  8939. img.addEventListener("error", errorHandler);
  8940. var noIndexedDB = function () {
  8941. img.src = url;
  8942. };
  8943. var loadFromIndexedDB = function () {
  8944. if (database) {
  8945. database.loadImageFromDB(url, img);
  8946. }
  8947. };
  8948. //ANY database to do!
  8949. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8950. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8951. }
  8952. else {
  8953. if (url.indexOf("file:") !== -1) {
  8954. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8955. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8956. try {
  8957. var blobURL;
  8958. try {
  8959. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8960. }
  8961. catch (ex) {
  8962. // Chrome doesn't support oneTimeOnly parameter
  8963. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8964. }
  8965. img.src = blobURL;
  8966. usingObjectURL = true;
  8967. }
  8968. catch (e) {
  8969. img.src = "";
  8970. }
  8971. return img;
  8972. }
  8973. }
  8974. noIndexedDB();
  8975. }
  8976. return img;
  8977. };
  8978. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8979. url = Tools.CleanUrl(url);
  8980. url = Tools.PreprocessUrl(url);
  8981. // If file and file input are set
  8982. if (url.indexOf("file:") !== -1) {
  8983. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8984. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8985. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8986. }
  8987. }
  8988. var loadUrl = Tools.BaseUrl + url;
  8989. var aborted = false;
  8990. var fileRequest = {
  8991. onCompleteObservable: new BABYLON.Observable(),
  8992. abort: function () { return aborted = true; },
  8993. };
  8994. var requestFile = function () {
  8995. var request = new XMLHttpRequest();
  8996. var retryHandle = null;
  8997. fileRequest.abort = function () {
  8998. aborted = true;
  8999. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9000. request.abort();
  9001. }
  9002. if (retryHandle !== null) {
  9003. clearTimeout(retryHandle);
  9004. retryHandle = null;
  9005. }
  9006. };
  9007. var retryLoop = function (retryIndex) {
  9008. request.open('GET', loadUrl, true);
  9009. if (useArrayBuffer) {
  9010. request.responseType = "arraybuffer";
  9011. }
  9012. if (onProgress) {
  9013. request.addEventListener("progress", onProgress);
  9014. }
  9015. var onLoadEnd = function () {
  9016. request.removeEventListener("loadend", onLoadEnd);
  9017. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9018. fileRequest.onCompleteObservable.clear();
  9019. };
  9020. request.addEventListener("loadend", onLoadEnd);
  9021. var onReadyStateChange = function () {
  9022. if (aborted) {
  9023. return;
  9024. }
  9025. // In case of undefined state in some browsers.
  9026. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9027. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9028. request.removeEventListener("readystatechange", onReadyStateChange);
  9029. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9030. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9031. return;
  9032. }
  9033. var retryStrategy = Tools.DefaultRetryStrategy;
  9034. if (retryStrategy) {
  9035. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9036. if (waitTime !== -1) {
  9037. // Prevent the request from completing for retry.
  9038. request.removeEventListener("loadend", onLoadEnd);
  9039. request = new XMLHttpRequest();
  9040. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9041. return;
  9042. }
  9043. }
  9044. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9045. if (onError) {
  9046. onError(request, e);
  9047. }
  9048. else {
  9049. throw e;
  9050. }
  9051. }
  9052. };
  9053. request.addEventListener("readystatechange", onReadyStateChange);
  9054. request.send();
  9055. };
  9056. retryLoop(0);
  9057. };
  9058. // Caching all files
  9059. if (database && database.enableSceneOffline) {
  9060. var noIndexedDB_1 = function () {
  9061. if (!aborted) {
  9062. requestFile();
  9063. }
  9064. };
  9065. var loadFromIndexedDB = function () {
  9066. // TODO: database needs to support aborting and should return a IFileRequest
  9067. if (aborted) {
  9068. return;
  9069. }
  9070. if (database) {
  9071. database.loadFileFromDB(url, function (data) {
  9072. if (!aborted) {
  9073. onSuccess(data);
  9074. }
  9075. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9076. }, onProgress ? function (event) {
  9077. if (!aborted) {
  9078. onProgress(event);
  9079. }
  9080. } : undefined, noIndexedDB_1, useArrayBuffer);
  9081. }
  9082. };
  9083. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9084. }
  9085. else {
  9086. requestFile();
  9087. }
  9088. return fileRequest;
  9089. };
  9090. /**
  9091. * Load a script (identified by an url). When the url returns, the
  9092. * content of this file is added into a new script element, attached to the DOM (body element)
  9093. */
  9094. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9095. var head = document.getElementsByTagName('head')[0];
  9096. var script = document.createElement('script');
  9097. script.type = 'text/javascript';
  9098. script.src = scriptUrl;
  9099. script.onload = function () {
  9100. if (onSuccess) {
  9101. onSuccess();
  9102. }
  9103. };
  9104. script.onerror = function (e) {
  9105. if (onError) {
  9106. onError("Unable to load script '" + scriptUrl + "'", e);
  9107. }
  9108. };
  9109. head.appendChild(script);
  9110. };
  9111. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9112. var reader = new FileReader();
  9113. var request = {
  9114. onCompleteObservable: new BABYLON.Observable(),
  9115. abort: function () { return reader.abort(); },
  9116. };
  9117. reader.onloadend = function (e) {
  9118. request.onCompleteObservable.notifyObservers(request);
  9119. };
  9120. reader.onload = function (e) {
  9121. //target doesn't have result from ts 1.3
  9122. callback(e.target['result']);
  9123. };
  9124. reader.onprogress = progressCallback;
  9125. reader.readAsDataURL(fileToLoad);
  9126. return request;
  9127. };
  9128. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9129. var reader = new FileReader();
  9130. var request = {
  9131. onCompleteObservable: new BABYLON.Observable(),
  9132. abort: function () { return reader.abort(); },
  9133. };
  9134. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9135. reader.onerror = function (e) {
  9136. Tools.Log("Error while reading file: " + fileToLoad.name);
  9137. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9138. };
  9139. reader.onload = function (e) {
  9140. //target doesn't have result from ts 1.3
  9141. callback(e.target['result']);
  9142. };
  9143. if (progressCallBack) {
  9144. reader.onprogress = progressCallBack;
  9145. }
  9146. if (!useArrayBuffer) {
  9147. // Asynchronous read
  9148. reader.readAsText(fileToLoad);
  9149. }
  9150. else {
  9151. reader.readAsArrayBuffer(fileToLoad);
  9152. }
  9153. return request;
  9154. };
  9155. //returns a downloadable url to a file content.
  9156. Tools.FileAsURL = function (content) {
  9157. var fileBlob = new Blob([content]);
  9158. var url = window.URL || window.webkitURL;
  9159. var link = url.createObjectURL(fileBlob);
  9160. return link;
  9161. };
  9162. // Misc.
  9163. Tools.Format = function (value, decimals) {
  9164. if (decimals === void 0) { decimals = 2; }
  9165. return value.toFixed(decimals);
  9166. };
  9167. Tools.CheckExtends = function (v, min, max) {
  9168. if (v.x < min.x)
  9169. min.x = v.x;
  9170. if (v.y < min.y)
  9171. min.y = v.y;
  9172. if (v.z < min.z)
  9173. min.z = v.z;
  9174. if (v.x > max.x)
  9175. max.x = v.x;
  9176. if (v.y > max.y)
  9177. max.y = v.y;
  9178. if (v.z > max.z)
  9179. max.z = v.z;
  9180. };
  9181. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9182. for (var prop in source) {
  9183. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9184. continue;
  9185. }
  9186. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9187. continue;
  9188. }
  9189. var sourceValue = source[prop];
  9190. var typeOfSourceValue = typeof sourceValue;
  9191. if (typeOfSourceValue === "function") {
  9192. continue;
  9193. }
  9194. try {
  9195. if (typeOfSourceValue === "object") {
  9196. if (sourceValue instanceof Array) {
  9197. destination[prop] = [];
  9198. if (sourceValue.length > 0) {
  9199. if (typeof sourceValue[0] == "object") {
  9200. for (var index = 0; index < sourceValue.length; index++) {
  9201. var clonedValue = cloneValue(sourceValue[index], destination);
  9202. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9203. destination[prop].push(clonedValue);
  9204. }
  9205. }
  9206. }
  9207. else {
  9208. destination[prop] = sourceValue.slice(0);
  9209. }
  9210. }
  9211. }
  9212. else {
  9213. destination[prop] = cloneValue(sourceValue, destination);
  9214. }
  9215. }
  9216. else {
  9217. destination[prop] = sourceValue;
  9218. }
  9219. }
  9220. catch (e) {
  9221. // Just ignore error (it could be because of a read-only property)
  9222. }
  9223. }
  9224. };
  9225. Tools.IsEmpty = function (obj) {
  9226. for (var i in obj) {
  9227. if (obj.hasOwnProperty(i)) {
  9228. return false;
  9229. }
  9230. }
  9231. return true;
  9232. };
  9233. Tools.RegisterTopRootEvents = function (events) {
  9234. for (var index = 0; index < events.length; index++) {
  9235. var event = events[index];
  9236. window.addEventListener(event.name, event.handler, false);
  9237. try {
  9238. if (window.parent) {
  9239. window.parent.addEventListener(event.name, event.handler, false);
  9240. }
  9241. }
  9242. catch (e) {
  9243. // Silently fails...
  9244. }
  9245. }
  9246. };
  9247. Tools.UnregisterTopRootEvents = function (events) {
  9248. for (var index = 0; index < events.length; index++) {
  9249. var event = events[index];
  9250. window.removeEventListener(event.name, event.handler);
  9251. try {
  9252. if (window.parent) {
  9253. window.parent.removeEventListener(event.name, event.handler);
  9254. }
  9255. }
  9256. catch (e) {
  9257. // Silently fails...
  9258. }
  9259. }
  9260. };
  9261. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9262. if (mimeType === void 0) { mimeType = "image/png"; }
  9263. // Read the contents of the framebuffer
  9264. var numberOfChannelsByLine = width * 4;
  9265. var halfHeight = height / 2;
  9266. //Reading datas from WebGL
  9267. var data = engine.readPixels(0, 0, width, height);
  9268. //To flip image on Y axis.
  9269. for (var i = 0; i < halfHeight; i++) {
  9270. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9271. var currentCell = j + i * numberOfChannelsByLine;
  9272. var targetLine = height - i - 1;
  9273. var targetCell = j + targetLine * numberOfChannelsByLine;
  9274. var temp = data[currentCell];
  9275. data[currentCell] = data[targetCell];
  9276. data[targetCell] = temp;
  9277. }
  9278. }
  9279. // Create a 2D canvas to store the result
  9280. if (!screenshotCanvas) {
  9281. screenshotCanvas = document.createElement('canvas');
  9282. }
  9283. screenshotCanvas.width = width;
  9284. screenshotCanvas.height = height;
  9285. var context = screenshotCanvas.getContext('2d');
  9286. if (context) {
  9287. // Copy the pixels to a 2D canvas
  9288. var imageData = context.createImageData(width, height);
  9289. var castData = (imageData.data);
  9290. castData.set(data);
  9291. context.putImageData(imageData, 0, 0);
  9292. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9293. }
  9294. };
  9295. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9296. if (mimeType === void 0) { mimeType = "image/png"; }
  9297. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9298. if (successCallback) {
  9299. successCallback(base64Image);
  9300. }
  9301. else {
  9302. // We need HTMLCanvasElement.toBlob for HD screenshots
  9303. if (!screenshotCanvas.toBlob) {
  9304. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9305. screenshotCanvas.toBlob = function (callback, type, quality) {
  9306. var _this = this;
  9307. setTimeout(function () {
  9308. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9309. for (var i = 0; i < len; i++) {
  9310. arr[i] = binStr.charCodeAt(i);
  9311. }
  9312. callback(new Blob([arr], { type: type || 'image/png' }));
  9313. });
  9314. };
  9315. }
  9316. screenshotCanvas.toBlob(function (blob) {
  9317. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9318. if (("download" in document.createElement("a"))) {
  9319. if (!fileName) {
  9320. var date = new Date();
  9321. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9322. fileName = "screenshot_" + stringDate + ".png";
  9323. }
  9324. Tools.Download(blob, fileName);
  9325. }
  9326. else {
  9327. var url = URL.createObjectURL(blob);
  9328. var newWindow = window.open("");
  9329. if (!newWindow)
  9330. return;
  9331. var img = newWindow.document.createElement("img");
  9332. img.onload = function () {
  9333. // no longer need to read the blob so it's revoked
  9334. URL.revokeObjectURL(url);
  9335. };
  9336. img.src = url;
  9337. newWindow.document.body.appendChild(img);
  9338. }
  9339. });
  9340. }
  9341. };
  9342. /**
  9343. * Downloads a blob in the browser
  9344. * @param blob defines the blob to download
  9345. * @param fileName defines the name of the downloaded file
  9346. */
  9347. Tools.Download = function (blob, fileName) {
  9348. var url = window.URL.createObjectURL(blob);
  9349. var a = document.createElement("a");
  9350. document.body.appendChild(a);
  9351. a.style.display = "none";
  9352. a.href = url;
  9353. a.download = fileName;
  9354. a.addEventListener("click", function () {
  9355. if (a.parentElement) {
  9356. a.parentElement.removeChild(a);
  9357. }
  9358. });
  9359. a.click();
  9360. window.URL.revokeObjectURL(url);
  9361. };
  9362. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9363. if (mimeType === void 0) { mimeType = "image/png"; }
  9364. var width;
  9365. var height;
  9366. // If a precision value is specified
  9367. if (size.precision) {
  9368. width = Math.round(engine.getRenderWidth() * size.precision);
  9369. height = Math.round(width / engine.getAspectRatio(camera));
  9370. }
  9371. else if (size.width && size.height) {
  9372. width = size.width;
  9373. height = size.height;
  9374. }
  9375. //If passing only width, computing height to keep display canvas ratio.
  9376. else if (size.width && !size.height) {
  9377. width = size.width;
  9378. height = Math.round(width / engine.getAspectRatio(camera));
  9379. }
  9380. //If passing only height, computing width to keep display canvas ratio.
  9381. else if (size.height && !size.width) {
  9382. height = size.height;
  9383. width = Math.round(height * engine.getAspectRatio(camera));
  9384. }
  9385. //Assuming here that "size" parameter is a number
  9386. else if (!isNaN(size)) {
  9387. height = size;
  9388. width = size;
  9389. }
  9390. else {
  9391. Tools.Error("Invalid 'size' parameter !");
  9392. return;
  9393. }
  9394. if (!screenshotCanvas) {
  9395. screenshotCanvas = document.createElement('canvas');
  9396. }
  9397. screenshotCanvas.width = width;
  9398. screenshotCanvas.height = height;
  9399. var renderContext = screenshotCanvas.getContext("2d");
  9400. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9401. var newWidth = width;
  9402. var newHeight = newWidth / ratio;
  9403. if (newHeight > height) {
  9404. newHeight = height;
  9405. newWidth = newHeight * ratio;
  9406. }
  9407. var offsetX = Math.max(0, width - newWidth) / 2;
  9408. var offsetY = Math.max(0, height - newHeight) / 2;
  9409. var renderingCanvas = engine.getRenderingCanvas();
  9410. if (renderContext && renderingCanvas) {
  9411. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9412. }
  9413. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9414. };
  9415. /**
  9416. * Generates an image screenshot from the specified camera.
  9417. *
  9418. * @param engine The engine to use for rendering
  9419. * @param camera The camera to use for rendering
  9420. * @param size This parameter can be set to a single number or to an object with the
  9421. * following (optional) properties: precision, width, height. If a single number is passed,
  9422. * it will be used for both width and height. If an object is passed, the screenshot size
  9423. * will be derived from the parameters. The precision property is a multiplier allowing
  9424. * rendering at a higher or lower resolution.
  9425. * @param successCallback The callback receives a single parameter which contains the
  9426. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9427. * src parameter of an <img> to display it.
  9428. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9429. * Check your browser for supported MIME types.
  9430. * @param samples Texture samples (default: 1)
  9431. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9432. * @param fileName A name for for the downloaded file.
  9433. * @constructor
  9434. */
  9435. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9436. if (mimeType === void 0) { mimeType = "image/png"; }
  9437. if (samples === void 0) { samples = 1; }
  9438. if (antialiasing === void 0) { antialiasing = false; }
  9439. var width;
  9440. var height;
  9441. //If a precision value is specified
  9442. if (size.precision) {
  9443. width = Math.round(engine.getRenderWidth() * size.precision);
  9444. height = Math.round(width / engine.getAspectRatio(camera));
  9445. size = { width: width, height: height };
  9446. }
  9447. else if (size.width && size.height) {
  9448. width = size.width;
  9449. height = size.height;
  9450. }
  9451. //If passing only width, computing height to keep display canvas ratio.
  9452. else if (size.width && !size.height) {
  9453. width = size.width;
  9454. height = Math.round(width / engine.getAspectRatio(camera));
  9455. size = { width: width, height: height };
  9456. }
  9457. //If passing only height, computing width to keep display canvas ratio.
  9458. else if (size.height && !size.width) {
  9459. height = size.height;
  9460. width = Math.round(height * engine.getAspectRatio(camera));
  9461. size = { width: width, height: height };
  9462. }
  9463. //Assuming here that "size" parameter is a number
  9464. else if (!isNaN(size)) {
  9465. height = size;
  9466. width = size;
  9467. }
  9468. else {
  9469. Tools.Error("Invalid 'size' parameter !");
  9470. return;
  9471. }
  9472. var scene = camera.getScene();
  9473. var previousCamera = null;
  9474. if (scene.activeCamera !== camera) {
  9475. previousCamera = scene.activeCamera;
  9476. scene.activeCamera = camera;
  9477. }
  9478. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9479. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9480. texture.renderList = null;
  9481. texture.samples = samples;
  9482. if (antialiasing) {
  9483. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9484. }
  9485. texture.onAfterRenderObservable.add(function () {
  9486. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9487. });
  9488. scene.incrementRenderId();
  9489. scene.resetCachedMaterial();
  9490. texture.render(true);
  9491. texture.dispose();
  9492. if (previousCamera) {
  9493. scene.activeCamera = previousCamera;
  9494. }
  9495. camera.getProjectionMatrix(true); // Force cache refresh;
  9496. };
  9497. // XHR response validator for local file scenario
  9498. Tools.ValidateXHRData = function (xhr, dataType) {
  9499. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9500. if (dataType === void 0) { dataType = 7; }
  9501. try {
  9502. if (dataType & 1) {
  9503. if (xhr.responseText && xhr.responseText.length > 0) {
  9504. return true;
  9505. }
  9506. else if (dataType === 1) {
  9507. return false;
  9508. }
  9509. }
  9510. if (dataType & 2) {
  9511. // Check header width and height since there is no "TGA" magic number
  9512. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9513. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9514. return true;
  9515. }
  9516. else if (dataType === 2) {
  9517. return false;
  9518. }
  9519. }
  9520. if (dataType & 4) {
  9521. // Check for the "DDS" magic number
  9522. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9523. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9524. return true;
  9525. }
  9526. else {
  9527. return false;
  9528. }
  9529. }
  9530. }
  9531. catch (e) {
  9532. // Global protection
  9533. }
  9534. return false;
  9535. };
  9536. /**
  9537. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9538. * Be aware Math.random() could cause collisions, but:
  9539. * "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"
  9540. */
  9541. Tools.RandomId = function () {
  9542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9544. return v.toString(16);
  9545. });
  9546. };
  9547. /**
  9548. * Test if the given uri is a base64 string.
  9549. * @param uri The uri to test
  9550. * @return True if the uri is a base64 string or false otherwise.
  9551. */
  9552. Tools.IsBase64 = function (uri) {
  9553. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9554. };
  9555. /**
  9556. * Decode the given base64 uri.
  9557. * @param uri The uri to decode
  9558. * @return The decoded base64 data.
  9559. */
  9560. Tools.DecodeBase64 = function (uri) {
  9561. var decodedString = atob(uri.split(",")[1]);
  9562. var bufferLength = decodedString.length;
  9563. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9564. for (var i = 0; i < bufferLength; i++) {
  9565. bufferView[i] = decodedString.charCodeAt(i);
  9566. }
  9567. return bufferView.buffer;
  9568. };
  9569. Object.defineProperty(Tools, "NoneLogLevel", {
  9570. get: function () {
  9571. return Tools._NoneLogLevel;
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(Tools, "MessageLogLevel", {
  9577. get: function () {
  9578. return Tools._MessageLogLevel;
  9579. },
  9580. enumerable: true,
  9581. configurable: true
  9582. });
  9583. Object.defineProperty(Tools, "WarningLogLevel", {
  9584. get: function () {
  9585. return Tools._WarningLogLevel;
  9586. },
  9587. enumerable: true,
  9588. configurable: true
  9589. });
  9590. Object.defineProperty(Tools, "ErrorLogLevel", {
  9591. get: function () {
  9592. return Tools._ErrorLogLevel;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(Tools, "AllLogLevel", {
  9598. get: function () {
  9599. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Tools._AddLogEntry = function (entry) {
  9605. Tools._LogCache = entry + Tools._LogCache;
  9606. if (Tools.OnNewCacheEntry) {
  9607. Tools.OnNewCacheEntry(entry);
  9608. }
  9609. };
  9610. Tools._FormatMessage = function (message) {
  9611. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9612. var date = new Date();
  9613. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9614. };
  9615. Tools._LogDisabled = function (message) {
  9616. // nothing to do
  9617. };
  9618. Tools._LogEnabled = function (message) {
  9619. var formattedMessage = Tools._FormatMessage(message);
  9620. console.log("BJS - " + formattedMessage);
  9621. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9622. Tools._AddLogEntry(entry);
  9623. };
  9624. Tools._WarnDisabled = function (message) {
  9625. // nothing to do
  9626. };
  9627. Tools._WarnEnabled = function (message) {
  9628. var formattedMessage = Tools._FormatMessage(message);
  9629. console.warn("BJS - " + formattedMessage);
  9630. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9631. Tools._AddLogEntry(entry);
  9632. };
  9633. Tools._ErrorDisabled = function (message) {
  9634. // nothing to do
  9635. };
  9636. Tools._ErrorEnabled = function (message) {
  9637. Tools.errorsCount++;
  9638. var formattedMessage = Tools._FormatMessage(message);
  9639. console.error("BJS - " + formattedMessage);
  9640. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9641. Tools._AddLogEntry(entry);
  9642. };
  9643. Object.defineProperty(Tools, "LogCache", {
  9644. get: function () {
  9645. return Tools._LogCache;
  9646. },
  9647. enumerable: true,
  9648. configurable: true
  9649. });
  9650. Tools.ClearLogCache = function () {
  9651. Tools._LogCache = "";
  9652. Tools.errorsCount = 0;
  9653. };
  9654. Object.defineProperty(Tools, "LogLevels", {
  9655. set: function (level) {
  9656. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9657. Tools.Log = Tools._LogEnabled;
  9658. }
  9659. else {
  9660. Tools.Log = Tools._LogDisabled;
  9661. }
  9662. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9663. Tools.Warn = Tools._WarnEnabled;
  9664. }
  9665. else {
  9666. Tools.Warn = Tools._WarnDisabled;
  9667. }
  9668. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9669. Tools.Error = Tools._ErrorEnabled;
  9670. }
  9671. else {
  9672. Tools.Error = Tools._ErrorDisabled;
  9673. }
  9674. },
  9675. enumerable: true,
  9676. configurable: true
  9677. });
  9678. Tools.IsWindowObjectExist = function () {
  9679. return (typeof window) !== "undefined";
  9680. };
  9681. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9682. get: function () {
  9683. return Tools._PerformanceNoneLogLevel;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9689. get: function () {
  9690. return Tools._PerformanceUserMarkLogLevel;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9696. get: function () {
  9697. return Tools._PerformanceConsoleLogLevel;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9703. set: function (level) {
  9704. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9705. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9706. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9707. return;
  9708. }
  9709. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9710. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9711. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9712. return;
  9713. }
  9714. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9715. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9721. };
  9722. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9723. };
  9724. Tools._StartUserMark = function (counterName, condition) {
  9725. if (condition === void 0) { condition = true; }
  9726. if (!Tools._performance) {
  9727. if (!Tools.IsWindowObjectExist()) {
  9728. return;
  9729. }
  9730. Tools._performance = window.performance;
  9731. }
  9732. if (!condition || !Tools._performance.mark) {
  9733. return;
  9734. }
  9735. Tools._performance.mark(counterName + "-Begin");
  9736. };
  9737. Tools._EndUserMark = function (counterName, condition) {
  9738. if (condition === void 0) { condition = true; }
  9739. if (!condition || !Tools._performance.mark) {
  9740. return;
  9741. }
  9742. Tools._performance.mark(counterName + "-End");
  9743. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9744. };
  9745. Tools._StartPerformanceConsole = function (counterName, condition) {
  9746. if (condition === void 0) { condition = true; }
  9747. if (!condition) {
  9748. return;
  9749. }
  9750. Tools._StartUserMark(counterName, condition);
  9751. if (console.time) {
  9752. console.time(counterName);
  9753. }
  9754. };
  9755. Tools._EndPerformanceConsole = function (counterName, condition) {
  9756. if (condition === void 0) { condition = true; }
  9757. if (!condition) {
  9758. return;
  9759. }
  9760. Tools._EndUserMark(counterName, condition);
  9761. if (console.time) {
  9762. console.timeEnd(counterName);
  9763. }
  9764. };
  9765. Object.defineProperty(Tools, "Now", {
  9766. get: function () {
  9767. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9768. return window.performance.now();
  9769. }
  9770. return Date.now();
  9771. },
  9772. enumerable: true,
  9773. configurable: true
  9774. });
  9775. /**
  9776. * This method will return the name of the class used to create the instance of the given object.
  9777. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9778. * @param object the object to get the class name from
  9779. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9780. */
  9781. Tools.GetClassName = function (object, isType) {
  9782. if (isType === void 0) { isType = false; }
  9783. var name = null;
  9784. if (!isType && object.getClassName) {
  9785. name = object.getClassName();
  9786. }
  9787. else {
  9788. if (object instanceof Object) {
  9789. var classObj = isType ? object : Object.getPrototypeOf(object);
  9790. name = classObj.constructor["__bjsclassName__"];
  9791. }
  9792. if (!name) {
  9793. name = typeof object;
  9794. }
  9795. }
  9796. return name;
  9797. };
  9798. Tools.First = function (array, predicate) {
  9799. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9800. var el = array_1[_i];
  9801. if (predicate(el)) {
  9802. return el;
  9803. }
  9804. }
  9805. return null;
  9806. };
  9807. /**
  9808. * This method will return the name of the full name of the class, including its owning module (if any).
  9809. * 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).
  9810. * @param object the object to get the class name from
  9811. * @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.
  9812. */
  9813. Tools.getFullClassName = function (object, isType) {
  9814. if (isType === void 0) { isType = false; }
  9815. var className = null;
  9816. var moduleName = null;
  9817. if (!isType && object.getClassName) {
  9818. className = object.getClassName();
  9819. }
  9820. else {
  9821. if (object instanceof Object) {
  9822. var classObj = isType ? object : Object.getPrototypeOf(object);
  9823. className = classObj.constructor["__bjsclassName__"];
  9824. moduleName = classObj.constructor["__bjsmoduleName__"];
  9825. }
  9826. if (!className) {
  9827. className = typeof object;
  9828. }
  9829. }
  9830. if (!className) {
  9831. return null;
  9832. }
  9833. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9834. };
  9835. /**
  9836. * 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.
  9837. * @param array
  9838. */
  9839. Tools.arrayOrStringFeeder = function (array) {
  9840. return function (index) {
  9841. if (index >= array.length) {
  9842. return null;
  9843. }
  9844. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9845. if (val && val.getHashCode) {
  9846. val = val.getHashCode();
  9847. }
  9848. if (typeof val === "string") {
  9849. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9850. }
  9851. return val;
  9852. };
  9853. };
  9854. /**
  9855. * Compute the hashCode of a stream of number
  9856. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9857. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9858. * @return the hash code computed
  9859. */
  9860. Tools.hashCodeFromStream = function (feeder) {
  9861. // Based from here: http://stackoverflow.com/a/7616484/802124
  9862. var hash = 0;
  9863. var index = 0;
  9864. var chr = feeder(index++);
  9865. while (chr != null) {
  9866. hash = ((hash << 5) - hash) + chr;
  9867. hash |= 0; // Convert to 32bit integer
  9868. chr = feeder(index++);
  9869. }
  9870. return hash;
  9871. };
  9872. /**
  9873. * Returns a promise that resolves after the given amount of time.
  9874. * @param delay Number of milliseconds to delay
  9875. * @returns Promise that resolves after the given amount of time
  9876. */
  9877. Tools.DelayAsync = function (delay) {
  9878. return new Promise(function (resolve) {
  9879. setTimeout(function () {
  9880. resolve();
  9881. }, delay);
  9882. });
  9883. };
  9884. /**
  9885. * Gets the current gradient from an array of IValueGradient
  9886. * @param ratio defines the current ratio to get
  9887. * @param gradients defines the array of IValueGradient
  9888. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9889. */
  9890. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9891. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9892. var currentGradient = gradients[gradientIndex];
  9893. var nextGradient = gradients[gradientIndex + 1];
  9894. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9895. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9896. updateFunc(currentGradient, nextGradient, scale);
  9897. }
  9898. }
  9899. };
  9900. Tools.BaseUrl = "";
  9901. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9902. /**
  9903. * Default behaviour for cors in the application.
  9904. * It can be a string if the expected behavior is identical in the entire app.
  9905. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9906. */
  9907. Tools.CorsBehavior = "anonymous";
  9908. Tools.UseFallbackTexture = true;
  9909. /**
  9910. * Use this object to register external classes like custom textures or material
  9911. * to allow the laoders to instantiate them
  9912. */
  9913. Tools.RegisteredExternalClasses = {};
  9914. // Used in case of a texture loading problem
  9915. 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";
  9916. Tools._tmpFloatArray = new Float32Array(1);
  9917. Tools.PreprocessUrl = function (url) {
  9918. return url;
  9919. };
  9920. // Logs
  9921. Tools._NoneLogLevel = 0;
  9922. Tools._MessageLogLevel = 1;
  9923. Tools._WarningLogLevel = 2;
  9924. Tools._ErrorLogLevel = 4;
  9925. Tools._LogCache = "";
  9926. Tools.errorsCount = 0;
  9927. Tools.Log = Tools._LogEnabled;
  9928. Tools.Warn = Tools._WarnEnabled;
  9929. Tools.Error = Tools._ErrorEnabled;
  9930. // Performances
  9931. Tools._PerformanceNoneLogLevel = 0;
  9932. Tools._PerformanceUserMarkLogLevel = 1;
  9933. Tools._PerformanceConsoleLogLevel = 2;
  9934. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9935. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9936. return Tools;
  9937. }());
  9938. BABYLON.Tools = Tools;
  9939. /**
  9940. * This class is used to track a performance counter which is number based.
  9941. * The user has access to many properties which give statistics of different nature
  9942. *
  9943. * The implementer can track two kinds of Performance Counter: time and count
  9944. * 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.
  9945. * 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.
  9946. */
  9947. var PerfCounter = /** @class */ (function () {
  9948. function PerfCounter() {
  9949. this._startMonitoringTime = 0;
  9950. this._min = 0;
  9951. this._max = 0;
  9952. this._average = 0;
  9953. this._lastSecAverage = 0;
  9954. this._current = 0;
  9955. this._totalValueCount = 0;
  9956. this._totalAccumulated = 0;
  9957. this._lastSecAccumulated = 0;
  9958. this._lastSecTime = 0;
  9959. this._lastSecValueCount = 0;
  9960. }
  9961. Object.defineProperty(PerfCounter.prototype, "min", {
  9962. /**
  9963. * Returns the smallest value ever
  9964. */
  9965. get: function () {
  9966. return this._min;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(PerfCounter.prototype, "max", {
  9972. /**
  9973. * Returns the biggest value ever
  9974. */
  9975. get: function () {
  9976. return this._max;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. Object.defineProperty(PerfCounter.prototype, "average", {
  9982. /**
  9983. * Returns the average value since the performance counter is running
  9984. */
  9985. get: function () {
  9986. return this._average;
  9987. },
  9988. enumerable: true,
  9989. configurable: true
  9990. });
  9991. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9992. /**
  9993. * Returns the average value of the last second the counter was monitored
  9994. */
  9995. get: function () {
  9996. return this._lastSecAverage;
  9997. },
  9998. enumerable: true,
  9999. configurable: true
  10000. });
  10001. Object.defineProperty(PerfCounter.prototype, "current", {
  10002. /**
  10003. * Returns the current value
  10004. */
  10005. get: function () {
  10006. return this._current;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(PerfCounter.prototype, "total", {
  10012. get: function () {
  10013. return this._totalAccumulated;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(PerfCounter.prototype, "count", {
  10019. get: function () {
  10020. return this._totalValueCount;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. /**
  10026. * Call this method to start monitoring a new frame.
  10027. * 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.
  10028. */
  10029. PerfCounter.prototype.fetchNewFrame = function () {
  10030. this._totalValueCount++;
  10031. this._current = 0;
  10032. this._lastSecValueCount++;
  10033. };
  10034. /**
  10035. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10036. * @param newCount the count value to add to the monitored count
  10037. * @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.
  10038. */
  10039. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10040. if (!PerfCounter.Enabled) {
  10041. return;
  10042. }
  10043. this._current += newCount;
  10044. if (fetchResult) {
  10045. this._fetchResult();
  10046. }
  10047. };
  10048. /**
  10049. * Start monitoring this performance counter
  10050. */
  10051. PerfCounter.prototype.beginMonitoring = function () {
  10052. if (!PerfCounter.Enabled) {
  10053. return;
  10054. }
  10055. this._startMonitoringTime = Tools.Now;
  10056. };
  10057. /**
  10058. * Compute the time lapsed since the previous beginMonitoring() call.
  10059. * @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
  10060. */
  10061. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10062. if (newFrame === void 0) { newFrame = true; }
  10063. if (!PerfCounter.Enabled) {
  10064. return;
  10065. }
  10066. if (newFrame) {
  10067. this.fetchNewFrame();
  10068. }
  10069. var currentTime = Tools.Now;
  10070. this._current = currentTime - this._startMonitoringTime;
  10071. if (newFrame) {
  10072. this._fetchResult();
  10073. }
  10074. };
  10075. PerfCounter.prototype._fetchResult = function () {
  10076. this._totalAccumulated += this._current;
  10077. this._lastSecAccumulated += this._current;
  10078. // Min/Max update
  10079. this._min = Math.min(this._min, this._current);
  10080. this._max = Math.max(this._max, this._current);
  10081. this._average = this._totalAccumulated / this._totalValueCount;
  10082. // Reset last sec?
  10083. var now = Tools.Now;
  10084. if ((now - this._lastSecTime) > 1000) {
  10085. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10086. this._lastSecTime = now;
  10087. this._lastSecAccumulated = 0;
  10088. this._lastSecValueCount = 0;
  10089. }
  10090. };
  10091. PerfCounter.Enabled = true;
  10092. return PerfCounter;
  10093. }());
  10094. BABYLON.PerfCounter = PerfCounter;
  10095. /**
  10096. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10097. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10098. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10099. * @param name The name of the class, case should be preserved
  10100. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10101. */
  10102. function className(name, module) {
  10103. return function (target) {
  10104. target["__bjsclassName__"] = name;
  10105. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10106. };
  10107. }
  10108. BABYLON.className = className;
  10109. /**
  10110. * An implementation of a loop for asynchronous functions.
  10111. */
  10112. var AsyncLoop = /** @class */ (function () {
  10113. /**
  10114. * Constroctor.
  10115. * @param iterations the number of iterations.
  10116. * @param _fn the function to run each iteration
  10117. * @param _successCallback the callback that will be called upon succesful execution
  10118. * @param offset starting offset.
  10119. */
  10120. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10121. if (offset === void 0) { offset = 0; }
  10122. this.iterations = iterations;
  10123. this._fn = _fn;
  10124. this._successCallback = _successCallback;
  10125. this.index = offset - 1;
  10126. this._done = false;
  10127. }
  10128. /**
  10129. * Execute the next iteration. Must be called after the last iteration was finished.
  10130. */
  10131. AsyncLoop.prototype.executeNext = function () {
  10132. if (!this._done) {
  10133. if (this.index + 1 < this.iterations) {
  10134. ++this.index;
  10135. this._fn(this);
  10136. }
  10137. else {
  10138. this.breakLoop();
  10139. }
  10140. }
  10141. };
  10142. /**
  10143. * Break the loop and run the success callback.
  10144. */
  10145. AsyncLoop.prototype.breakLoop = function () {
  10146. this._done = true;
  10147. this._successCallback();
  10148. };
  10149. /**
  10150. * Helper function
  10151. */
  10152. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10153. if (offset === void 0) { offset = 0; }
  10154. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10155. loop.executeNext();
  10156. return loop;
  10157. };
  10158. /**
  10159. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10160. * @param iterations total number of iterations
  10161. * @param syncedIterations number of synchronous iterations in each async iteration.
  10162. * @param fn the function to call each iteration.
  10163. * @param callback a success call back that will be called when iterating stops.
  10164. * @param breakFunction a break condition (optional)
  10165. * @param timeout timeout settings for the setTimeout function. default - 0.
  10166. * @constructor
  10167. */
  10168. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10169. if (timeout === void 0) { timeout = 0; }
  10170. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10171. if (breakFunction && breakFunction())
  10172. loop.breakLoop();
  10173. else {
  10174. setTimeout(function () {
  10175. for (var i = 0; i < syncedIterations; ++i) {
  10176. var iteration = (loop.index * syncedIterations) + i;
  10177. if (iteration >= iterations)
  10178. break;
  10179. fn(iteration);
  10180. if (breakFunction && breakFunction()) {
  10181. loop.breakLoop();
  10182. break;
  10183. }
  10184. }
  10185. loop.executeNext();
  10186. }, timeout);
  10187. }
  10188. }, callback);
  10189. };
  10190. return AsyncLoop;
  10191. }());
  10192. BABYLON.AsyncLoop = AsyncLoop;
  10193. })(BABYLON || (BABYLON = {}));
  10194. //# sourceMappingURL=babylon.tools.js.map
  10195. var BABYLON;
  10196. (function (BABYLON) {
  10197. var PromiseStates;
  10198. (function (PromiseStates) {
  10199. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10200. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10201. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10202. })(PromiseStates || (PromiseStates = {}));
  10203. var FulFillmentAgregator = /** @class */ (function () {
  10204. function FulFillmentAgregator() {
  10205. this.count = 0;
  10206. this.target = 0;
  10207. this.results = [];
  10208. }
  10209. return FulFillmentAgregator;
  10210. }());
  10211. var InternalPromise = /** @class */ (function () {
  10212. function InternalPromise(resolver) {
  10213. var _this = this;
  10214. this._state = PromiseStates.Pending;
  10215. this._children = new Array();
  10216. this._rejectWasConsumed = false;
  10217. if (!resolver) {
  10218. return;
  10219. }
  10220. try {
  10221. resolver(function (value) {
  10222. _this._resolve(value);
  10223. }, function (reason) {
  10224. _this._reject(reason);
  10225. });
  10226. }
  10227. catch (e) {
  10228. this._reject(e);
  10229. }
  10230. }
  10231. Object.defineProperty(InternalPromise.prototype, "_result", {
  10232. get: function () {
  10233. return this._resultValue;
  10234. },
  10235. set: function (value) {
  10236. this._resultValue = value;
  10237. if (this._parent && this._parent._result === undefined) {
  10238. this._parent._result = value;
  10239. }
  10240. },
  10241. enumerable: true,
  10242. configurable: true
  10243. });
  10244. InternalPromise.prototype.catch = function (onRejected) {
  10245. return this.then(undefined, onRejected);
  10246. };
  10247. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10248. var _this = this;
  10249. var newPromise = new InternalPromise();
  10250. newPromise._onFulfilled = onFulfilled;
  10251. newPromise._onRejected = onRejected;
  10252. // Composition
  10253. this._children.push(newPromise);
  10254. newPromise._parent = this;
  10255. if (this._state !== PromiseStates.Pending) {
  10256. BABYLON.Tools.SetImmediate(function () {
  10257. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10258. var returnedValue = newPromise._resolve(_this._result);
  10259. if (returnedValue !== undefined && returnedValue !== null) {
  10260. if (returnedValue._state !== undefined) {
  10261. var returnedPromise = returnedValue;
  10262. newPromise._children.push(returnedPromise);
  10263. returnedPromise._parent = newPromise;
  10264. newPromise = returnedPromise;
  10265. }
  10266. else {
  10267. newPromise._result = returnedValue;
  10268. }
  10269. }
  10270. }
  10271. else {
  10272. newPromise._reject(_this._reason);
  10273. }
  10274. });
  10275. }
  10276. return newPromise;
  10277. };
  10278. InternalPromise.prototype._moveChildren = function (children) {
  10279. var _this = this;
  10280. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10281. this._children.forEach(function (child) {
  10282. child._parent = _this;
  10283. });
  10284. if (this._state === PromiseStates.Fulfilled) {
  10285. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10286. var child = _b[_i];
  10287. child._resolve(this._result);
  10288. }
  10289. }
  10290. else if (this._state === PromiseStates.Rejected) {
  10291. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10292. var child = _d[_c];
  10293. child._reject(this._reason);
  10294. }
  10295. }
  10296. var _a;
  10297. };
  10298. InternalPromise.prototype._resolve = function (value) {
  10299. try {
  10300. this._state = PromiseStates.Fulfilled;
  10301. var returnedValue = null;
  10302. if (this._onFulfilled) {
  10303. returnedValue = this._onFulfilled(value);
  10304. }
  10305. if (returnedValue !== undefined && returnedValue !== null) {
  10306. if (returnedValue._state !== undefined) {
  10307. // Transmit children
  10308. var returnedPromise = returnedValue;
  10309. returnedPromise._parent = this;
  10310. returnedPromise._moveChildren(this._children);
  10311. value = returnedPromise._result;
  10312. }
  10313. else {
  10314. value = returnedValue;
  10315. }
  10316. }
  10317. this._result = value;
  10318. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10319. var child = _a[_i];
  10320. child._resolve(value);
  10321. }
  10322. this._children.length = 0;
  10323. delete this._onFulfilled;
  10324. delete this._onRejected;
  10325. }
  10326. catch (e) {
  10327. this._reject(e, true);
  10328. }
  10329. };
  10330. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10331. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10332. this._state = PromiseStates.Rejected;
  10333. this._reason = reason;
  10334. if (this._onRejected && !onLocalThrow) {
  10335. try {
  10336. this._onRejected(reason);
  10337. this._rejectWasConsumed = true;
  10338. }
  10339. catch (e) {
  10340. reason = e;
  10341. }
  10342. }
  10343. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10344. var child = _a[_i];
  10345. if (this._rejectWasConsumed) {
  10346. child._resolve(null);
  10347. }
  10348. else {
  10349. child._reject(reason);
  10350. }
  10351. }
  10352. this._children.length = 0;
  10353. delete this._onFulfilled;
  10354. delete this._onRejected;
  10355. };
  10356. InternalPromise.resolve = function (value) {
  10357. var newPromise = new InternalPromise();
  10358. newPromise._resolve(value);
  10359. return newPromise;
  10360. };
  10361. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10362. promise.then(function (value) {
  10363. agregator.results[index] = value;
  10364. agregator.count++;
  10365. if (agregator.count === agregator.target) {
  10366. agregator.rootPromise._resolve(agregator.results);
  10367. }
  10368. return null;
  10369. }, function (reason) {
  10370. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10371. agregator.rootPromise._reject(reason);
  10372. }
  10373. });
  10374. };
  10375. InternalPromise.all = function (promises) {
  10376. var newPromise = new InternalPromise();
  10377. var agregator = new FulFillmentAgregator();
  10378. agregator.target = promises.length;
  10379. agregator.rootPromise = newPromise;
  10380. if (promises.length) {
  10381. for (var index = 0; index < promises.length; index++) {
  10382. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10383. }
  10384. }
  10385. else {
  10386. newPromise._resolve([]);
  10387. }
  10388. return newPromise;
  10389. };
  10390. InternalPromise.race = function (promises) {
  10391. var newPromise = new InternalPromise();
  10392. if (promises.length) {
  10393. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10394. var promise = promises_1[_i];
  10395. promise.then(function (value) {
  10396. if (newPromise) {
  10397. newPromise._resolve(value);
  10398. newPromise = null;
  10399. }
  10400. return null;
  10401. }, function (reason) {
  10402. if (newPromise) {
  10403. newPromise._reject(reason);
  10404. newPromise = null;
  10405. }
  10406. });
  10407. }
  10408. }
  10409. return newPromise;
  10410. };
  10411. return InternalPromise;
  10412. }());
  10413. /**
  10414. * Helper class that provides a small promise polyfill
  10415. */
  10416. var PromisePolyfill = /** @class */ (function () {
  10417. function PromisePolyfill() {
  10418. }
  10419. /**
  10420. * Static function used to check if the polyfill is required
  10421. * If this is the case then the function will inject the polyfill to window.Promise
  10422. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10423. */
  10424. PromisePolyfill.Apply = function (force) {
  10425. if (force === void 0) { force = false; }
  10426. if (force || typeof Promise === 'undefined') {
  10427. var root = window;
  10428. root.Promise = InternalPromise;
  10429. }
  10430. };
  10431. return PromisePolyfill;
  10432. }());
  10433. BABYLON.PromisePolyfill = PromisePolyfill;
  10434. })(BABYLON || (BABYLON = {}));
  10435. //# sourceMappingURL=babylon.promise.js.map
  10436. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10437. var BABYLON;
  10438. (function (BABYLON) {
  10439. /**
  10440. * Helper class to push actions to a pool of workers.
  10441. */
  10442. var WorkerPool = /** @class */ (function () {
  10443. /**
  10444. * Constructor
  10445. * @param workers Array of workers to use for actions
  10446. */
  10447. function WorkerPool(workers) {
  10448. this._pendingActions = new Array();
  10449. this._workerInfos = workers.map(function (worker) { return ({
  10450. worker: worker,
  10451. active: false
  10452. }); });
  10453. }
  10454. /**
  10455. * Terminates all workers and clears any pending actions.
  10456. */
  10457. WorkerPool.prototype.dispose = function () {
  10458. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10459. var workerInfo = _a[_i];
  10460. workerInfo.worker.terminate();
  10461. }
  10462. delete this._workerInfos;
  10463. delete this._pendingActions;
  10464. };
  10465. /**
  10466. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10467. * pended until a worker has completed its action.
  10468. * @param action The action to perform. Call onComplete when the action is complete.
  10469. */
  10470. WorkerPool.prototype.push = function (action) {
  10471. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10472. var workerInfo = _a[_i];
  10473. if (!workerInfo.active) {
  10474. this._execute(workerInfo, action);
  10475. return;
  10476. }
  10477. }
  10478. this._pendingActions.push(action);
  10479. };
  10480. WorkerPool.prototype._execute = function (workerInfo, action) {
  10481. var _this = this;
  10482. workerInfo.active = true;
  10483. action(workerInfo.worker, function () {
  10484. workerInfo.active = false;
  10485. var nextAction = _this._pendingActions.shift();
  10486. if (nextAction) {
  10487. _this._execute(workerInfo, nextAction);
  10488. }
  10489. });
  10490. };
  10491. return WorkerPool;
  10492. }());
  10493. BABYLON.WorkerPool = WorkerPool;
  10494. })(BABYLON || (BABYLON = {}));
  10495. //# sourceMappingURL=babylon.workerPool.js.map
  10496. var BABYLON;
  10497. (function (BABYLON) {
  10498. /**
  10499. * @hidden
  10500. **/
  10501. var _AlphaState = /** @class */ (function () {
  10502. /**
  10503. * Initializes the state.
  10504. */
  10505. function _AlphaState() {
  10506. this._isAlphaBlendDirty = false;
  10507. this._isBlendFunctionParametersDirty = false;
  10508. this._isBlendEquationParametersDirty = false;
  10509. this._isBlendConstantsDirty = false;
  10510. this._alphaBlend = false;
  10511. this._blendFunctionParameters = new Array(4);
  10512. this._blendEquationParameters = new Array(2);
  10513. this._blendConstants = new Array(4);
  10514. this.reset();
  10515. }
  10516. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10517. get: function () {
  10518. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10524. get: function () {
  10525. return this._alphaBlend;
  10526. },
  10527. set: function (value) {
  10528. if (this._alphaBlend === value) {
  10529. return;
  10530. }
  10531. this._alphaBlend = value;
  10532. this._isAlphaBlendDirty = true;
  10533. },
  10534. enumerable: true,
  10535. configurable: true
  10536. });
  10537. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10538. if (this._blendConstants[0] === r &&
  10539. this._blendConstants[1] === g &&
  10540. this._blendConstants[2] === b &&
  10541. this._blendConstants[3] === a) {
  10542. return;
  10543. }
  10544. this._blendConstants[0] = r;
  10545. this._blendConstants[1] = g;
  10546. this._blendConstants[2] = b;
  10547. this._blendConstants[3] = a;
  10548. this._isBlendConstantsDirty = true;
  10549. };
  10550. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10551. if (this._blendFunctionParameters[0] === value0 &&
  10552. this._blendFunctionParameters[1] === value1 &&
  10553. this._blendFunctionParameters[2] === value2 &&
  10554. this._blendFunctionParameters[3] === value3) {
  10555. return;
  10556. }
  10557. this._blendFunctionParameters[0] = value0;
  10558. this._blendFunctionParameters[1] = value1;
  10559. this._blendFunctionParameters[2] = value2;
  10560. this._blendFunctionParameters[3] = value3;
  10561. this._isBlendFunctionParametersDirty = true;
  10562. };
  10563. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10564. if (this._blendEquationParameters[0] === rgb &&
  10565. this._blendEquationParameters[1] === alpha) {
  10566. return;
  10567. }
  10568. this._blendEquationParameters[0] = rgb;
  10569. this._blendEquationParameters[1] = alpha;
  10570. this._isBlendEquationParametersDirty = true;
  10571. };
  10572. _AlphaState.prototype.reset = function () {
  10573. this._alphaBlend = false;
  10574. this._blendFunctionParameters[0] = null;
  10575. this._blendFunctionParameters[1] = null;
  10576. this._blendFunctionParameters[2] = null;
  10577. this._blendFunctionParameters[3] = null;
  10578. this._blendEquationParameters[0] = null;
  10579. this._blendEquationParameters[1] = null;
  10580. this._blendConstants[0] = null;
  10581. this._blendConstants[1] = null;
  10582. this._blendConstants[2] = null;
  10583. this._blendConstants[3] = null;
  10584. this._isAlphaBlendDirty = true;
  10585. this._isBlendFunctionParametersDirty = false;
  10586. this._isBlendEquationParametersDirty = false;
  10587. this._isBlendConstantsDirty = false;
  10588. };
  10589. _AlphaState.prototype.apply = function (gl) {
  10590. if (!this.isDirty) {
  10591. return;
  10592. }
  10593. // Alpha blend
  10594. if (this._isAlphaBlendDirty) {
  10595. if (this._alphaBlend) {
  10596. gl.enable(gl.BLEND);
  10597. }
  10598. else {
  10599. gl.disable(gl.BLEND);
  10600. }
  10601. this._isAlphaBlendDirty = false;
  10602. }
  10603. // Alpha function
  10604. if (this._isBlendFunctionParametersDirty) {
  10605. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10606. this._isBlendFunctionParametersDirty = false;
  10607. }
  10608. // Alpha equation
  10609. if (this._isBlendEquationParametersDirty) {
  10610. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10611. this._isBlendEquationParametersDirty = false;
  10612. }
  10613. // Constants
  10614. if (this._isBlendConstantsDirty) {
  10615. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10616. this._isBlendConstantsDirty = false;
  10617. }
  10618. };
  10619. return _AlphaState;
  10620. }());
  10621. BABYLON._AlphaState = _AlphaState;
  10622. })(BABYLON || (BABYLON = {}));
  10623. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10624. var BABYLON;
  10625. (function (BABYLON) {
  10626. /**
  10627. * @hidden
  10628. **/
  10629. var _DepthCullingState = /** @class */ (function () {
  10630. /**
  10631. * Initializes the state.
  10632. */
  10633. function _DepthCullingState() {
  10634. this._isDepthTestDirty = false;
  10635. this._isDepthMaskDirty = false;
  10636. this._isDepthFuncDirty = false;
  10637. this._isCullFaceDirty = false;
  10638. this._isCullDirty = false;
  10639. this._isZOffsetDirty = false;
  10640. this._isFrontFaceDirty = false;
  10641. this.reset();
  10642. }
  10643. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10644. get: function () {
  10645. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10646. },
  10647. enumerable: true,
  10648. configurable: true
  10649. });
  10650. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10651. get: function () {
  10652. return this._zOffset;
  10653. },
  10654. set: function (value) {
  10655. if (this._zOffset === value) {
  10656. return;
  10657. }
  10658. this._zOffset = value;
  10659. this._isZOffsetDirty = true;
  10660. },
  10661. enumerable: true,
  10662. configurable: true
  10663. });
  10664. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10665. get: function () {
  10666. return this._cullFace;
  10667. },
  10668. set: function (value) {
  10669. if (this._cullFace === value) {
  10670. return;
  10671. }
  10672. this._cullFace = value;
  10673. this._isCullFaceDirty = true;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10679. get: function () {
  10680. return this._cull;
  10681. },
  10682. set: function (value) {
  10683. if (this._cull === value) {
  10684. return;
  10685. }
  10686. this._cull = value;
  10687. this._isCullDirty = true;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10693. get: function () {
  10694. return this._depthFunc;
  10695. },
  10696. set: function (value) {
  10697. if (this._depthFunc === value) {
  10698. return;
  10699. }
  10700. this._depthFunc = value;
  10701. this._isDepthFuncDirty = true;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10707. get: function () {
  10708. return this._depthMask;
  10709. },
  10710. set: function (value) {
  10711. if (this._depthMask === value) {
  10712. return;
  10713. }
  10714. this._depthMask = value;
  10715. this._isDepthMaskDirty = true;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10721. get: function () {
  10722. return this._depthTest;
  10723. },
  10724. set: function (value) {
  10725. if (this._depthTest === value) {
  10726. return;
  10727. }
  10728. this._depthTest = value;
  10729. this._isDepthTestDirty = true;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10735. get: function () {
  10736. return this._frontFace;
  10737. },
  10738. set: function (value) {
  10739. if (this._frontFace === value) {
  10740. return;
  10741. }
  10742. this._frontFace = value;
  10743. this._isFrontFaceDirty = true;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. _DepthCullingState.prototype.reset = function () {
  10749. this._depthMask = true;
  10750. this._depthTest = true;
  10751. this._depthFunc = null;
  10752. this._cullFace = null;
  10753. this._cull = null;
  10754. this._zOffset = 0;
  10755. this._frontFace = null;
  10756. this._isDepthTestDirty = true;
  10757. this._isDepthMaskDirty = true;
  10758. this._isDepthFuncDirty = false;
  10759. this._isCullFaceDirty = false;
  10760. this._isCullDirty = false;
  10761. this._isZOffsetDirty = false;
  10762. this._isFrontFaceDirty = false;
  10763. };
  10764. _DepthCullingState.prototype.apply = function (gl) {
  10765. if (!this.isDirty) {
  10766. return;
  10767. }
  10768. // Cull
  10769. if (this._isCullDirty) {
  10770. if (this.cull) {
  10771. gl.enable(gl.CULL_FACE);
  10772. }
  10773. else {
  10774. gl.disable(gl.CULL_FACE);
  10775. }
  10776. this._isCullDirty = false;
  10777. }
  10778. // Cull face
  10779. if (this._isCullFaceDirty) {
  10780. gl.cullFace(this.cullFace);
  10781. this._isCullFaceDirty = false;
  10782. }
  10783. // Depth mask
  10784. if (this._isDepthMaskDirty) {
  10785. gl.depthMask(this.depthMask);
  10786. this._isDepthMaskDirty = false;
  10787. }
  10788. // Depth test
  10789. if (this._isDepthTestDirty) {
  10790. if (this.depthTest) {
  10791. gl.enable(gl.DEPTH_TEST);
  10792. }
  10793. else {
  10794. gl.disable(gl.DEPTH_TEST);
  10795. }
  10796. this._isDepthTestDirty = false;
  10797. }
  10798. // Depth func
  10799. if (this._isDepthFuncDirty) {
  10800. gl.depthFunc(this.depthFunc);
  10801. this._isDepthFuncDirty = false;
  10802. }
  10803. // zOffset
  10804. if (this._isZOffsetDirty) {
  10805. if (this.zOffset) {
  10806. gl.enable(gl.POLYGON_OFFSET_FILL);
  10807. gl.polygonOffset(this.zOffset, 0);
  10808. }
  10809. else {
  10810. gl.disable(gl.POLYGON_OFFSET_FILL);
  10811. }
  10812. this._isZOffsetDirty = false;
  10813. }
  10814. // Front face
  10815. if (this._isFrontFaceDirty) {
  10816. gl.frontFace(this.frontFace);
  10817. this._isFrontFaceDirty = false;
  10818. }
  10819. };
  10820. return _DepthCullingState;
  10821. }());
  10822. BABYLON._DepthCullingState = _DepthCullingState;
  10823. })(BABYLON || (BABYLON = {}));
  10824. //# sourceMappingURL=babylon.depthCullingState.js.map
  10825. var BABYLON;
  10826. (function (BABYLON) {
  10827. /**
  10828. * @hidden
  10829. **/
  10830. var _StencilState = /** @class */ (function () {
  10831. function _StencilState() {
  10832. this._isStencilTestDirty = false;
  10833. this._isStencilMaskDirty = false;
  10834. this._isStencilFuncDirty = false;
  10835. this._isStencilOpDirty = false;
  10836. this.reset();
  10837. }
  10838. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10839. get: function () {
  10840. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10841. },
  10842. enumerable: true,
  10843. configurable: true
  10844. });
  10845. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10846. get: function () {
  10847. return this._stencilFunc;
  10848. },
  10849. set: function (value) {
  10850. if (this._stencilFunc === value) {
  10851. return;
  10852. }
  10853. this._stencilFunc = value;
  10854. this._isStencilFuncDirty = true;
  10855. },
  10856. enumerable: true,
  10857. configurable: true
  10858. });
  10859. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10860. get: function () {
  10861. return this._stencilFuncRef;
  10862. },
  10863. set: function (value) {
  10864. if (this._stencilFuncRef === value) {
  10865. return;
  10866. }
  10867. this._stencilFuncRef = value;
  10868. this._isStencilFuncDirty = true;
  10869. },
  10870. enumerable: true,
  10871. configurable: true
  10872. });
  10873. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10874. get: function () {
  10875. return this._stencilFuncMask;
  10876. },
  10877. set: function (value) {
  10878. if (this._stencilFuncMask === value) {
  10879. return;
  10880. }
  10881. this._stencilFuncMask = value;
  10882. this._isStencilFuncDirty = true;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10888. get: function () {
  10889. return this._stencilOpStencilFail;
  10890. },
  10891. set: function (value) {
  10892. if (this._stencilOpStencilFail === value) {
  10893. return;
  10894. }
  10895. this._stencilOpStencilFail = value;
  10896. this._isStencilOpDirty = true;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10902. get: function () {
  10903. return this._stencilOpDepthFail;
  10904. },
  10905. set: function (value) {
  10906. if (this._stencilOpDepthFail === value) {
  10907. return;
  10908. }
  10909. this._stencilOpDepthFail = value;
  10910. this._isStencilOpDirty = true;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10916. get: function () {
  10917. return this._stencilOpStencilDepthPass;
  10918. },
  10919. set: function (value) {
  10920. if (this._stencilOpStencilDepthPass === value) {
  10921. return;
  10922. }
  10923. this._stencilOpStencilDepthPass = value;
  10924. this._isStencilOpDirty = true;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10930. get: function () {
  10931. return this._stencilMask;
  10932. },
  10933. set: function (value) {
  10934. if (this._stencilMask === value) {
  10935. return;
  10936. }
  10937. this._stencilMask = value;
  10938. this._isStencilMaskDirty = true;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10944. get: function () {
  10945. return this._stencilTest;
  10946. },
  10947. set: function (value) {
  10948. if (this._stencilTest === value) {
  10949. return;
  10950. }
  10951. this._stencilTest = value;
  10952. this._isStencilTestDirty = true;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. _StencilState.prototype.reset = function () {
  10958. this._stencilTest = false;
  10959. this._stencilMask = 0xFF;
  10960. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10961. this._stencilFuncRef = 1;
  10962. this._stencilFuncMask = 0xFF;
  10963. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10964. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10965. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10966. this._isStencilTestDirty = true;
  10967. this._isStencilMaskDirty = true;
  10968. this._isStencilFuncDirty = true;
  10969. this._isStencilOpDirty = true;
  10970. };
  10971. _StencilState.prototype.apply = function (gl) {
  10972. if (!this.isDirty) {
  10973. return;
  10974. }
  10975. // Stencil test
  10976. if (this._isStencilTestDirty) {
  10977. if (this.stencilTest) {
  10978. gl.enable(gl.STENCIL_TEST);
  10979. }
  10980. else {
  10981. gl.disable(gl.STENCIL_TEST);
  10982. }
  10983. this._isStencilTestDirty = false;
  10984. }
  10985. // Stencil mask
  10986. if (this._isStencilMaskDirty) {
  10987. gl.stencilMask(this.stencilMask);
  10988. this._isStencilMaskDirty = false;
  10989. }
  10990. // Stencil func
  10991. if (this._isStencilFuncDirty) {
  10992. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10993. this._isStencilFuncDirty = false;
  10994. }
  10995. // Stencil op
  10996. if (this._isStencilOpDirty) {
  10997. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10998. this._isStencilOpDirty = false;
  10999. }
  11000. };
  11001. return _StencilState;
  11002. }());
  11003. BABYLON._StencilState = _StencilState;
  11004. })(BABYLON || (BABYLON = {}));
  11005. //# sourceMappingURL=babylon.stencilState.js.map
  11006. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11007. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11008. s = arguments[i];
  11009. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11010. t[p] = s[p];
  11011. }
  11012. return t;
  11013. };
  11014. var BABYLON;
  11015. (function (BABYLON) {
  11016. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11017. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11018. };
  11019. var compileRawShader = function (gl, source, type) {
  11020. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11021. gl.shaderSource(shader, source);
  11022. gl.compileShader(shader);
  11023. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11024. var log = gl.getShaderInfoLog(shader);
  11025. if (log) {
  11026. throw new Error(log);
  11027. }
  11028. }
  11029. if (!shader) {
  11030. throw new Error("Something went wrong while compile the shader.");
  11031. }
  11032. return shader;
  11033. };
  11034. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11035. var magFilter = gl.NEAREST;
  11036. var minFilter = gl.NEAREST;
  11037. switch (samplingMode) {
  11038. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11039. magFilter = gl.LINEAR;
  11040. if (generateMipMaps) {
  11041. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11042. }
  11043. else {
  11044. minFilter = gl.LINEAR;
  11045. }
  11046. break;
  11047. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11048. magFilter = gl.LINEAR;
  11049. if (generateMipMaps) {
  11050. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11051. }
  11052. else {
  11053. minFilter = gl.LINEAR;
  11054. }
  11055. break;
  11056. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11057. magFilter = gl.NEAREST;
  11058. if (generateMipMaps) {
  11059. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11060. }
  11061. else {
  11062. minFilter = gl.NEAREST;
  11063. }
  11064. break;
  11065. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11066. magFilter = gl.NEAREST;
  11067. if (generateMipMaps) {
  11068. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11069. }
  11070. else {
  11071. minFilter = gl.NEAREST;
  11072. }
  11073. break;
  11074. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11075. magFilter = gl.NEAREST;
  11076. if (generateMipMaps) {
  11077. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11078. }
  11079. else {
  11080. minFilter = gl.LINEAR;
  11081. }
  11082. break;
  11083. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11084. magFilter = gl.NEAREST;
  11085. if (generateMipMaps) {
  11086. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11087. }
  11088. else {
  11089. minFilter = gl.LINEAR;
  11090. }
  11091. break;
  11092. case BABYLON.Texture.NEAREST_LINEAR:
  11093. magFilter = gl.NEAREST;
  11094. minFilter = gl.LINEAR;
  11095. break;
  11096. case BABYLON.Texture.NEAREST_NEAREST:
  11097. magFilter = gl.NEAREST;
  11098. minFilter = gl.NEAREST;
  11099. break;
  11100. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11101. magFilter = gl.LINEAR;
  11102. if (generateMipMaps) {
  11103. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11104. }
  11105. else {
  11106. minFilter = gl.NEAREST;
  11107. }
  11108. break;
  11109. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11110. magFilter = gl.LINEAR;
  11111. if (generateMipMaps) {
  11112. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11113. }
  11114. else {
  11115. minFilter = gl.NEAREST;
  11116. }
  11117. break;
  11118. case BABYLON.Texture.LINEAR_LINEAR:
  11119. magFilter = gl.LINEAR;
  11120. minFilter = gl.LINEAR;
  11121. break;
  11122. case BABYLON.Texture.LINEAR_NEAREST:
  11123. magFilter = gl.LINEAR;
  11124. minFilter = gl.NEAREST;
  11125. break;
  11126. }
  11127. return {
  11128. min: minFilter,
  11129. mag: magFilter
  11130. };
  11131. };
  11132. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11133. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11134. var img;
  11135. var onload = function () {
  11136. loadedImages[index] = img;
  11137. loadedImages._internalCount++;
  11138. if (scene) {
  11139. scene._removePendingData(img);
  11140. }
  11141. if (loadedImages._internalCount === 6) {
  11142. onfinish(loadedImages);
  11143. }
  11144. };
  11145. var onerror = function (message, exception) {
  11146. if (scene) {
  11147. scene._removePendingData(img);
  11148. }
  11149. if (onErrorCallBack) {
  11150. onErrorCallBack(message, exception);
  11151. }
  11152. };
  11153. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11154. if (scene) {
  11155. scene._addPendingData(img);
  11156. }
  11157. };
  11158. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11159. if (onError === void 0) { onError = null; }
  11160. var loadedImages = [];
  11161. loadedImages._internalCount = 0;
  11162. for (var index = 0; index < 6; index++) {
  11163. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11164. }
  11165. };
  11166. var BufferPointer = /** @class */ (function () {
  11167. function BufferPointer() {
  11168. }
  11169. return BufferPointer;
  11170. }());
  11171. /**
  11172. * Interface for attribute information associated with buffer instanciation
  11173. */
  11174. var InstancingAttributeInfo = /** @class */ (function () {
  11175. function InstancingAttributeInfo() {
  11176. }
  11177. return InstancingAttributeInfo;
  11178. }());
  11179. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11180. /**
  11181. * Define options used to create a render target texture
  11182. */
  11183. var RenderTargetCreationOptions = /** @class */ (function () {
  11184. function RenderTargetCreationOptions() {
  11185. }
  11186. return RenderTargetCreationOptions;
  11187. }());
  11188. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11189. /**
  11190. * Define options used to create a depth texture
  11191. */
  11192. var DepthTextureCreationOptions = /** @class */ (function () {
  11193. function DepthTextureCreationOptions() {
  11194. }
  11195. return DepthTextureCreationOptions;
  11196. }());
  11197. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11198. /**
  11199. * Class used to describe the capabilities of the engine relatively to the current browser
  11200. */
  11201. var EngineCapabilities = /** @class */ (function () {
  11202. function EngineCapabilities() {
  11203. }
  11204. return EngineCapabilities;
  11205. }());
  11206. BABYLON.EngineCapabilities = EngineCapabilities;
  11207. /**
  11208. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11209. */
  11210. var Engine = /** @class */ (function () {
  11211. /**
  11212. * Creates a new engine
  11213. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11214. * @param antialias defines enable antialiasing (default: false)
  11215. * @param options defines further options to be sent to the getContext() function
  11216. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11217. */
  11218. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11219. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11220. var _this = this;
  11221. // Public members
  11222. /**
  11223. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11224. */
  11225. this.forcePOTTextures = false;
  11226. /**
  11227. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11228. */
  11229. this.isFullscreen = false;
  11230. /**
  11231. * Gets a boolean indicating if the pointer is currently locked
  11232. */
  11233. this.isPointerLock = false;
  11234. /**
  11235. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11236. */
  11237. this.cullBackFaces = true;
  11238. /**
  11239. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11240. */
  11241. this.renderEvenInBackground = true;
  11242. /**
  11243. * Gets or sets a boolean indicating that cache can be kept between frames
  11244. */
  11245. this.preventCacheWipeBetweenFrames = false;
  11246. /**
  11247. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11248. **/
  11249. this.enableOfflineSupport = false;
  11250. /**
  11251. * 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)
  11252. **/
  11253. this.disableManifestCheck = false;
  11254. /**
  11255. * Gets the list of created scenes
  11256. */
  11257. this.scenes = new Array();
  11258. /**
  11259. * Gets the list of created postprocesses
  11260. */
  11261. this.postProcesses = new Array();
  11262. // Observables
  11263. /**
  11264. * Observable event triggered each time the rendering canvas is resized
  11265. */
  11266. this.onResizeObservable = new BABYLON.Observable();
  11267. /**
  11268. * Observable event triggered each time the canvas loses focus
  11269. */
  11270. this.onCanvasBlurObservable = new BABYLON.Observable();
  11271. /**
  11272. * Observable event triggered each time the canvas gains focus
  11273. */
  11274. this.onCanvasFocusObservable = new BABYLON.Observable();
  11275. /**
  11276. * Observable event triggered each time the canvas receives pointerout event
  11277. */
  11278. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11279. /**
  11280. * Observable event triggered before each texture is initialized
  11281. */
  11282. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11283. //WebVR
  11284. this._vrDisplay = undefined;
  11285. this._vrSupported = false;
  11286. this._vrExclusivePointerMode = false;
  11287. // Uniform buffers list
  11288. /**
  11289. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11290. */
  11291. this.disableUniformBuffers = false;
  11292. /** @hidden */
  11293. this._uniformBuffers = new Array();
  11294. // Observables
  11295. /**
  11296. * Observable raised when the engine begins a new frame
  11297. */
  11298. this.onBeginFrameObservable = new BABYLON.Observable();
  11299. /**
  11300. * Observable raised when the engine ends the current frame
  11301. */
  11302. this.onEndFrameObservable = new BABYLON.Observable();
  11303. /**
  11304. * Observable raised when the engine is about to compile a shader
  11305. */
  11306. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11307. /**
  11308. * Observable raised when the engine has jsut compiled a shader
  11309. */
  11310. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11311. this._windowIsBackground = false;
  11312. this._webGLVersion = 1.0;
  11313. /** @hidden */
  11314. this._badOS = false;
  11315. /** @hidden */
  11316. this._badDesktopOS = false;
  11317. /**
  11318. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11319. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11320. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11321. */
  11322. this.disableTextureBindingOptimization = false;
  11323. /**
  11324. * Observable signaled when VR display mode changes
  11325. */
  11326. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11327. /**
  11328. * Observable signaled when VR request present is complete
  11329. */
  11330. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11331. /**
  11332. * Observable signaled when VR request present starts
  11333. */
  11334. this.onVRRequestPresentStart = new BABYLON.Observable();
  11335. this._colorWrite = true;
  11336. /** @hidden */
  11337. this._drawCalls = new BABYLON.PerfCounter();
  11338. /** @hidden */
  11339. this._textureCollisions = new BABYLON.PerfCounter();
  11340. this._renderingQueueLaunched = false;
  11341. this._activeRenderLoops = new Array();
  11342. // Deterministic lockstepMaxSteps
  11343. this._deterministicLockstep = false;
  11344. this._lockstepMaxSteps = 4;
  11345. // Lost context
  11346. /**
  11347. * Observable signaled when a context lost event is raised
  11348. */
  11349. this.onContextLostObservable = new BABYLON.Observable();
  11350. /**
  11351. * Observable signaled when a context restored event is raised
  11352. */
  11353. this.onContextRestoredObservable = new BABYLON.Observable();
  11354. this._contextWasLost = false;
  11355. this._doNotHandleContextLost = false;
  11356. // FPS
  11357. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11358. this._fps = 60;
  11359. this._deltaTime = 0;
  11360. /**
  11361. * Turn this value on if you want to pause FPS computation when in background
  11362. */
  11363. this.disablePerformanceMonitorInBackground = false;
  11364. // States
  11365. /** @hidden */
  11366. this._depthCullingState = new BABYLON._DepthCullingState();
  11367. /** @hidden */
  11368. this._stencilState = new BABYLON._StencilState();
  11369. /** @hidden */
  11370. this._alphaState = new BABYLON._AlphaState();
  11371. /** @hidden */
  11372. this._alphaMode = Engine.ALPHA_DISABLE;
  11373. // Cache
  11374. this._internalTexturesCache = new Array();
  11375. /** @hidden */
  11376. this._activeChannel = 0;
  11377. this._currentTextureChannel = -1;
  11378. /** @hidden */
  11379. this._boundTexturesCache = {};
  11380. this._compiledEffects = {};
  11381. this._vertexAttribArraysEnabled = [];
  11382. this._uintIndicesCurrentlySet = false;
  11383. this._currentBoundBuffer = new Array();
  11384. this._currentBufferPointers = new Array();
  11385. this._currentInstanceLocations = new Array();
  11386. this._currentInstanceBuffers = new Array();
  11387. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11388. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11389. this._vaoRecordInProgress = false;
  11390. this._mustWipeVertexAttributes = false;
  11391. this._nextFreeTextureSlots = new Array();
  11392. this._maxSimultaneousTextures = 0;
  11393. this._activeRequests = new Array();
  11394. // Hardware supported Compressed Textures
  11395. this._texturesSupported = new Array();
  11396. /**
  11397. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11398. */
  11399. this.premultipliedAlpha = true;
  11400. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11401. this._onVRFullScreenTriggered = function () {
  11402. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11403. //get the old size before we change
  11404. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11405. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11406. //get the width and height, change the render size
  11407. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11408. _this.setHardwareScalingLevel(1);
  11409. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11410. }
  11411. else {
  11412. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11413. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11414. }
  11415. };
  11416. this._unpackFlipYCached = null;
  11417. this._boundUniforms = {};
  11418. // Register promises
  11419. BABYLON.PromisePolyfill.Apply();
  11420. var canvas = null;
  11421. Engine.Instances.push(this);
  11422. if (!canvasOrContext) {
  11423. return;
  11424. }
  11425. options = options || {};
  11426. if (canvasOrContext.getContext) {
  11427. canvas = canvasOrContext;
  11428. this._renderingCanvas = canvas;
  11429. if (antialias != null) {
  11430. options.antialias = antialias;
  11431. }
  11432. if (options.deterministicLockstep === undefined) {
  11433. options.deterministicLockstep = false;
  11434. }
  11435. if (options.lockstepMaxSteps === undefined) {
  11436. options.lockstepMaxSteps = 4;
  11437. }
  11438. if (options.preserveDrawingBuffer === undefined) {
  11439. options.preserveDrawingBuffer = false;
  11440. }
  11441. if (options.audioEngine === undefined) {
  11442. options.audioEngine = true;
  11443. }
  11444. if (options.stencil === undefined) {
  11445. options.stencil = true;
  11446. }
  11447. if (options.premultipliedAlpha === false) {
  11448. this.premultipliedAlpha = false;
  11449. }
  11450. this._deterministicLockstep = options.deterministicLockstep;
  11451. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11452. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11453. // Exceptions
  11454. if (navigator && navigator.userAgent) {
  11455. var ua = navigator.userAgent;
  11456. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11457. var exception = _a[_i];
  11458. var key = exception.key;
  11459. var targets = exception.targets;
  11460. if (ua.indexOf(key) > -1) {
  11461. if (exception.capture && exception.captureConstraint) {
  11462. var capture = exception.capture;
  11463. var constraint = exception.captureConstraint;
  11464. var regex = new RegExp(capture);
  11465. var matches = regex.exec(ua);
  11466. if (matches && matches.length > 0) {
  11467. var capturedValue = parseInt(matches[matches.length - 1]);
  11468. if (capturedValue >= constraint) {
  11469. continue;
  11470. }
  11471. }
  11472. }
  11473. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11474. var target = targets_1[_b];
  11475. switch (target) {
  11476. case "uniformBuffer":
  11477. this.disableUniformBuffers = true;
  11478. break;
  11479. case "textureBindingOptimization":
  11480. this.disableTextureBindingOptimization = true;
  11481. break;
  11482. }
  11483. }
  11484. }
  11485. }
  11486. }
  11487. // GL
  11488. if (!options.disableWebGL2Support) {
  11489. try {
  11490. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11491. if (this._gl) {
  11492. this._webGLVersion = 2.0;
  11493. }
  11494. }
  11495. catch (e) {
  11496. // Do nothing
  11497. }
  11498. }
  11499. if (!this._gl) {
  11500. if (!canvas) {
  11501. throw new Error("The provided canvas is null or undefined.");
  11502. }
  11503. try {
  11504. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11505. }
  11506. catch (e) {
  11507. throw new Error("WebGL not supported");
  11508. }
  11509. }
  11510. if (!this._gl) {
  11511. throw new Error("WebGL not supported");
  11512. }
  11513. this._onCanvasFocus = function () {
  11514. _this.onCanvasFocusObservable.notifyObservers(_this);
  11515. };
  11516. this._onCanvasBlur = function () {
  11517. _this.onCanvasBlurObservable.notifyObservers(_this);
  11518. };
  11519. canvas.addEventListener("focus", this._onCanvasFocus);
  11520. canvas.addEventListener("blur", this._onCanvasBlur);
  11521. this._onBlur = function () {
  11522. if (_this.disablePerformanceMonitorInBackground) {
  11523. _this._performanceMonitor.disable();
  11524. }
  11525. _this._windowIsBackground = true;
  11526. };
  11527. this._onFocus = function () {
  11528. if (_this.disablePerformanceMonitorInBackground) {
  11529. _this._performanceMonitor.enable();
  11530. }
  11531. _this._windowIsBackground = false;
  11532. };
  11533. this._onCanvasPointerOut = function (ev) {
  11534. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11535. };
  11536. window.addEventListener("blur", this._onBlur);
  11537. window.addEventListener("focus", this._onFocus);
  11538. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11539. // Context lost
  11540. if (!this._doNotHandleContextLost) {
  11541. this._onContextLost = function (evt) {
  11542. evt.preventDefault();
  11543. _this._contextWasLost = true;
  11544. BABYLON.Tools.Warn("WebGL context lost.");
  11545. _this.onContextLostObservable.notifyObservers(_this);
  11546. };
  11547. this._onContextRestored = function (evt) {
  11548. // Adding a timeout to avoid race condition at browser level
  11549. setTimeout(function () {
  11550. // Rebuild gl context
  11551. _this._initGLContext();
  11552. // Rebuild effects
  11553. _this._rebuildEffects();
  11554. // Rebuild textures
  11555. _this._rebuildInternalTextures();
  11556. // Rebuild buffers
  11557. _this._rebuildBuffers();
  11558. // Cache
  11559. _this.wipeCaches(true);
  11560. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11561. _this.onContextRestoredObservable.notifyObservers(_this);
  11562. _this._contextWasLost = false;
  11563. }, 0);
  11564. };
  11565. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11566. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11567. }
  11568. }
  11569. else {
  11570. this._gl = canvasOrContext;
  11571. this._renderingCanvas = this._gl.canvas;
  11572. if (this._gl.renderbufferStorageMultisample) {
  11573. this._webGLVersion = 2.0;
  11574. }
  11575. options.stencil = this._gl.getContextAttributes().stencil;
  11576. }
  11577. // Viewport
  11578. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11579. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11580. this.resize();
  11581. this._isStencilEnable = options.stencil ? true : false;
  11582. this._initGLContext();
  11583. if (canvas) {
  11584. // Fullscreen
  11585. this._onFullscreenChange = function () {
  11586. if (document.fullscreen !== undefined) {
  11587. _this.isFullscreen = document.fullscreen;
  11588. }
  11589. else if (document.mozFullScreen !== undefined) {
  11590. _this.isFullscreen = document.mozFullScreen;
  11591. }
  11592. else if (document.webkitIsFullScreen !== undefined) {
  11593. _this.isFullscreen = document.webkitIsFullScreen;
  11594. }
  11595. else if (document.msIsFullScreen !== undefined) {
  11596. _this.isFullscreen = document.msIsFullScreen;
  11597. }
  11598. // Pointer lock
  11599. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11600. canvas.requestPointerLock = canvas.requestPointerLock ||
  11601. canvas.msRequestPointerLock ||
  11602. canvas.mozRequestPointerLock ||
  11603. canvas.webkitRequestPointerLock;
  11604. if (canvas.requestPointerLock) {
  11605. canvas.requestPointerLock();
  11606. }
  11607. }
  11608. };
  11609. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11610. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11611. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11612. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11613. // Pointer lock
  11614. this._onPointerLockChange = function () {
  11615. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11616. document.webkitPointerLockElement === canvas ||
  11617. document.msPointerLockElement === canvas ||
  11618. document.pointerLockElement === canvas);
  11619. };
  11620. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11621. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11622. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11623. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11624. this._onVRDisplayPointerRestricted = function () {
  11625. if (canvas) {
  11626. canvas.requestPointerLock();
  11627. }
  11628. };
  11629. this._onVRDisplayPointerUnrestricted = function () {
  11630. document.exitPointerLock();
  11631. };
  11632. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11633. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11634. }
  11635. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11636. Engine.audioEngine = new BABYLON.AudioEngine();
  11637. }
  11638. // Prepare buffer pointers
  11639. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11640. this._currentBufferPointers[i] = new BufferPointer();
  11641. }
  11642. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11643. // Load WebVR Devices
  11644. if (options.autoEnableWebVR) {
  11645. this.initWebVR();
  11646. }
  11647. // Detect if we are running on a faulty buggy OS.
  11648. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11649. // Detect if we are running on a faulty buggy desktop OS.
  11650. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11651. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11652. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11653. }
  11654. Object.defineProperty(Engine, "LastCreatedEngine", {
  11655. /**
  11656. * Gets the latest created engine
  11657. */
  11658. get: function () {
  11659. if (Engine.Instances.length === 0) {
  11660. return null;
  11661. }
  11662. return Engine.Instances[Engine.Instances.length - 1];
  11663. },
  11664. enumerable: true,
  11665. configurable: true
  11666. });
  11667. Object.defineProperty(Engine, "LastCreatedScene", {
  11668. /**
  11669. * Gets the latest created scene
  11670. */
  11671. get: function () {
  11672. var lastCreatedEngine = Engine.LastCreatedEngine;
  11673. if (!lastCreatedEngine) {
  11674. return null;
  11675. }
  11676. if (lastCreatedEngine.scenes.length === 0) {
  11677. return null;
  11678. }
  11679. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. /**
  11685. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11686. * @param flag defines which part of the materials must be marked as dirty
  11687. * @param predicate defines a predicate used to filter which materials should be affected
  11688. */
  11689. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11690. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11691. var engine = Engine.Instances[engineIndex];
  11692. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11693. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11694. }
  11695. }
  11696. };
  11697. Object.defineProperty(Engine, "NEVER", {
  11698. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11699. get: function () {
  11700. return Engine._NEVER;
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Engine, "ALWAYS", {
  11706. /** 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 */
  11707. get: function () {
  11708. return Engine._ALWAYS;
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(Engine, "LESS", {
  11714. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11715. get: function () {
  11716. return Engine._LESS;
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Engine, "EQUAL", {
  11722. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11723. get: function () {
  11724. return Engine._EQUAL;
  11725. },
  11726. enumerable: true,
  11727. configurable: true
  11728. });
  11729. Object.defineProperty(Engine, "LEQUAL", {
  11730. /** 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 */
  11731. get: function () {
  11732. return Engine._LEQUAL;
  11733. },
  11734. enumerable: true,
  11735. configurable: true
  11736. });
  11737. Object.defineProperty(Engine, "GREATER", {
  11738. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11739. get: function () {
  11740. return Engine._GREATER;
  11741. },
  11742. enumerable: true,
  11743. configurable: true
  11744. });
  11745. Object.defineProperty(Engine, "GEQUAL", {
  11746. /** 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 */
  11747. get: function () {
  11748. return Engine._GEQUAL;
  11749. },
  11750. enumerable: true,
  11751. configurable: true
  11752. });
  11753. Object.defineProperty(Engine, "NOTEQUAL", {
  11754. /** 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 */
  11755. get: function () {
  11756. return Engine._NOTEQUAL;
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Object.defineProperty(Engine, "KEEP", {
  11762. /** Passed to stencilOperation to specify that stencil value must be kept */
  11763. get: function () {
  11764. return Engine._KEEP;
  11765. },
  11766. enumerable: true,
  11767. configurable: true
  11768. });
  11769. Object.defineProperty(Engine, "REPLACE", {
  11770. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11771. get: function () {
  11772. return Engine._REPLACE;
  11773. },
  11774. enumerable: true,
  11775. configurable: true
  11776. });
  11777. Object.defineProperty(Engine, "INCR", {
  11778. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11779. get: function () {
  11780. return Engine._INCR;
  11781. },
  11782. enumerable: true,
  11783. configurable: true
  11784. });
  11785. Object.defineProperty(Engine, "DECR", {
  11786. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11787. get: function () {
  11788. return Engine._DECR;
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. Object.defineProperty(Engine, "INVERT", {
  11794. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11795. get: function () {
  11796. return Engine._INVERT;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "INCR_WRAP", {
  11802. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11803. get: function () {
  11804. return Engine._INCR_WRAP;
  11805. },
  11806. enumerable: true,
  11807. configurable: true
  11808. });
  11809. Object.defineProperty(Engine, "DECR_WRAP", {
  11810. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11811. get: function () {
  11812. return Engine._DECR_WRAP;
  11813. },
  11814. enumerable: true,
  11815. configurable: true
  11816. });
  11817. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11818. // Alpha
  11819. /** Defines that alpha blending is disabled */
  11820. get: function () {
  11821. return Engine._ALPHA_DISABLE;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11827. /** Defines that alpha blending to SRC + DEST */
  11828. get: function () {
  11829. return Engine._ALPHA_ONEONE;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "ALPHA_ADD", {
  11835. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11836. get: function () {
  11837. return Engine._ALPHA_ADD;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11843. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11844. get: function () {
  11845. return Engine._ALPHA_COMBINE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11851. /** Defines that alpha blending to DEST - SRC * DEST */
  11852. get: function () {
  11853. return Engine._ALPHA_SUBTRACT;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11859. /** Defines that alpha blending to SRC * DEST */
  11860. get: function () {
  11861. return Engine._ALPHA_MULTIPLY;
  11862. },
  11863. enumerable: true,
  11864. configurable: true
  11865. });
  11866. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11867. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11868. get: function () {
  11869. return Engine._ALPHA_MAXIMIZED;
  11870. },
  11871. enumerable: true,
  11872. configurable: true
  11873. });
  11874. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11875. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11876. get: function () {
  11877. return Engine._ALPHA_PREMULTIPLIED;
  11878. },
  11879. enumerable: true,
  11880. configurable: true
  11881. });
  11882. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11883. /**
  11884. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11885. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11886. */
  11887. get: function () {
  11888. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11894. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11895. get: function () {
  11896. return Engine._ALPHA_INTERPOLATE;
  11897. },
  11898. enumerable: true,
  11899. configurable: true
  11900. });
  11901. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11902. /**
  11903. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11904. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11905. */
  11906. get: function () {
  11907. return Engine._ALPHA_SCREENMODE;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11913. // Delays
  11914. /** Defines that the ressource is not delayed*/
  11915. get: function () {
  11916. return Engine._DELAYLOADSTATE_NONE;
  11917. },
  11918. enumerable: true,
  11919. configurable: true
  11920. });
  11921. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11922. /** Defines that the ressource was successfully delay loaded */
  11923. get: function () {
  11924. return Engine._DELAYLOADSTATE_LOADED;
  11925. },
  11926. enumerable: true,
  11927. configurable: true
  11928. });
  11929. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11930. /** Defines that the ressource is currently delay loading */
  11931. get: function () {
  11932. return Engine._DELAYLOADSTATE_LOADING;
  11933. },
  11934. enumerable: true,
  11935. configurable: true
  11936. });
  11937. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11938. /** Defines that the ressource is delayed and has not started loading */
  11939. get: function () {
  11940. return Engine._DELAYLOADSTATE_NOTLOADED;
  11941. },
  11942. enumerable: true,
  11943. configurable: true
  11944. });
  11945. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11946. /** ALPHA */
  11947. get: function () {
  11948. return Engine._TEXTUREFORMAT_ALPHA;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11954. /** LUMINANCE */
  11955. get: function () {
  11956. return Engine._TEXTUREFORMAT_LUMINANCE;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  11962. /**
  11963. * R
  11964. */
  11965. get: function () {
  11966. return Engine._TEXTUREFORMAT_R;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  11972. /**
  11973. * RG
  11974. */
  11975. get: function () {
  11976. return Engine._TEXTUREFORMAT_RG;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11982. /** LUMINANCE_ALPHA */
  11983. get: function () {
  11984. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11990. /** RGB */
  11991. get: function () {
  11992. return Engine._TEXTUREFORMAT_RGB;
  11993. },
  11994. enumerable: true,
  11995. configurable: true
  11996. });
  11997. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11998. /** RGBA */
  11999. get: function () {
  12000. return Engine._TEXTUREFORMAT_RGBA;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12006. /** UNSIGNED_INT */
  12007. get: function () {
  12008. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12014. /** FLOAT */
  12015. get: function () {
  12016. return Engine._TEXTURETYPE_FLOAT;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12022. /** HALF_FLOAT */
  12023. get: function () {
  12024. return Engine._TEXTURETYPE_HALF_FLOAT;
  12025. },
  12026. enumerable: true,
  12027. configurable: true
  12028. });
  12029. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12030. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12031. get: function () {
  12032. return Engine._SCALEMODE_FLOOR;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12038. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12039. get: function () {
  12040. return Engine._SCALEMODE_NEAREST;
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12046. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12047. get: function () {
  12048. return Engine._SCALEMODE_CEILING;
  12049. },
  12050. enumerable: true,
  12051. configurable: true
  12052. });
  12053. Object.defineProperty(Engine, "Version", {
  12054. /**
  12055. * Returns the current version of the framework
  12056. */
  12057. get: function () {
  12058. return "3.3.0-alpha.8";
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12064. /**
  12065. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12066. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12067. */
  12068. get: function () {
  12069. return this._vrExclusivePointerMode;
  12070. },
  12071. enumerable: true,
  12072. configurable: true
  12073. });
  12074. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12075. /**
  12076. * Gets a boolean indicating that the engine supports uniform buffers
  12077. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12078. */
  12079. get: function () {
  12080. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12081. },
  12082. enumerable: true,
  12083. configurable: true
  12084. });
  12085. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12086. /**
  12087. * Gets a boolean indicating that only power of 2 textures are supported
  12088. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12089. */
  12090. get: function () {
  12091. return this._webGLVersion < 2 || this.forcePOTTextures;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12097. /**
  12098. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12099. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12100. */
  12101. get: function () {
  12102. return this._doNotHandleContextLost;
  12103. },
  12104. set: function (value) {
  12105. this._doNotHandleContextLost = value;
  12106. },
  12107. enumerable: true,
  12108. configurable: true
  12109. });
  12110. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12111. /**
  12112. * Gets the performance monitor attached to this engine
  12113. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12114. */
  12115. get: function () {
  12116. return this._performanceMonitor;
  12117. },
  12118. enumerable: true,
  12119. configurable: true
  12120. });
  12121. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12122. /**
  12123. * Gets the list of texture formats supported
  12124. */
  12125. get: function () {
  12126. return this._texturesSupported;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12132. /**
  12133. * Gets the list of texture formats in use
  12134. */
  12135. get: function () {
  12136. return this._textureFormatInUse;
  12137. },
  12138. enumerable: true,
  12139. configurable: true
  12140. });
  12141. Object.defineProperty(Engine.prototype, "currentViewport", {
  12142. /**
  12143. * Gets the current viewport
  12144. */
  12145. get: function () {
  12146. return this._cachedViewport;
  12147. },
  12148. enumerable: true,
  12149. configurable: true
  12150. });
  12151. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12152. /**
  12153. * Gets the default empty texture
  12154. */
  12155. get: function () {
  12156. if (!this._emptyTexture) {
  12157. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12158. }
  12159. return this._emptyTexture;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12165. /**
  12166. * Gets the default empty 3D texture
  12167. */
  12168. get: function () {
  12169. if (!this._emptyTexture3D) {
  12170. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12171. }
  12172. return this._emptyTexture3D;
  12173. },
  12174. enumerable: true,
  12175. configurable: true
  12176. });
  12177. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12178. /**
  12179. * Gets the default empty cube texture
  12180. */
  12181. get: function () {
  12182. if (!this._emptyCubeTexture) {
  12183. var faceData = new Uint8Array(4);
  12184. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12185. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12186. }
  12187. return this._emptyCubeTexture;
  12188. },
  12189. enumerable: true,
  12190. configurable: true
  12191. });
  12192. Engine.prototype._rebuildInternalTextures = function () {
  12193. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12194. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12195. var internalTexture = currentState_1[_i];
  12196. internalTexture._rebuild();
  12197. }
  12198. };
  12199. Engine.prototype._rebuildEffects = function () {
  12200. for (var key in this._compiledEffects) {
  12201. var effect = this._compiledEffects[key];
  12202. effect._prepareEffect();
  12203. }
  12204. BABYLON.Effect.ResetCache();
  12205. };
  12206. Engine.prototype._rebuildBuffers = function () {
  12207. // Index / Vertex
  12208. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12209. var scene = _a[_i];
  12210. scene.resetCachedMaterial();
  12211. scene._rebuildGeometries();
  12212. scene._rebuildTextures();
  12213. }
  12214. // Uniforms
  12215. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12216. var uniformBuffer = _c[_b];
  12217. uniformBuffer._rebuild();
  12218. }
  12219. };
  12220. Engine.prototype._initGLContext = function () {
  12221. // Caps
  12222. this._caps = new EngineCapabilities();
  12223. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12224. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12225. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12226. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12227. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12228. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12229. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12230. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12231. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12232. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12233. // Infos
  12234. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12235. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12236. if (rendererInfo != null) {
  12237. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12238. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12239. }
  12240. if (!this._glVendor) {
  12241. this._glVendor = "Unknown vendor";
  12242. }
  12243. if (!this._glRenderer) {
  12244. this._glRenderer = "Unknown renderer";
  12245. }
  12246. // Constants
  12247. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12248. if (this._gl.RGBA16F !== 0x881A) {
  12249. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12250. }
  12251. if (this._gl.RGBA32F !== 0x8814) {
  12252. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12253. }
  12254. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12255. this._gl.DEPTH24_STENCIL8 = 35056;
  12256. }
  12257. // Extensions
  12258. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12259. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12260. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12261. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12262. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12263. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12264. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12265. 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');
  12266. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12267. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12268. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12269. this._caps.highPrecisionShaderSupported = true;
  12270. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12271. if (this._caps.timerQuery) {
  12272. if (this._webGLVersion === 1) {
  12273. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12274. }
  12275. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12276. }
  12277. // Checks if some of the format renders first to allow the use of webgl inspector.
  12278. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12279. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12280. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12281. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12282. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12283. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12284. if (this._webGLVersion > 1) {
  12285. this._gl.HALF_FLOAT_OES = 0x140B;
  12286. }
  12287. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12288. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12289. // Draw buffers
  12290. if (this._webGLVersion > 1) {
  12291. this._caps.drawBuffersExtension = true;
  12292. }
  12293. else {
  12294. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12295. if (drawBuffersExtension !== null) {
  12296. this._caps.drawBuffersExtension = true;
  12297. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12298. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12299. for (var i = 0; i < 16; i++) {
  12300. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12301. }
  12302. }
  12303. else {
  12304. this._caps.drawBuffersExtension = false;
  12305. }
  12306. }
  12307. // Depth Texture
  12308. if (this._webGLVersion > 1) {
  12309. this._caps.depthTextureExtension = true;
  12310. }
  12311. else {
  12312. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12313. if (depthTextureExtension != null) {
  12314. this._caps.depthTextureExtension = true;
  12315. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12316. }
  12317. }
  12318. // Vertex array object
  12319. if (this._webGLVersion > 1) {
  12320. this._caps.vertexArrayObject = true;
  12321. }
  12322. else {
  12323. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12324. if (vertexArrayObjectExtension != null) {
  12325. this._caps.vertexArrayObject = true;
  12326. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12327. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12328. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12329. }
  12330. else {
  12331. this._caps.vertexArrayObject = false;
  12332. }
  12333. }
  12334. // Instances count
  12335. if (this._webGLVersion > 1) {
  12336. this._caps.instancedArrays = true;
  12337. }
  12338. else {
  12339. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12340. if (instanceExtension != null) {
  12341. this._caps.instancedArrays = true;
  12342. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12343. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12344. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12345. }
  12346. else {
  12347. this._caps.instancedArrays = false;
  12348. }
  12349. }
  12350. // Intelligently add supported compressed formats in order to check for.
  12351. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12352. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12353. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12354. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12355. if (this._caps.astc)
  12356. this.texturesSupported.push('-astc.ktx');
  12357. if (this._caps.s3tc)
  12358. this.texturesSupported.push('-dxt.ktx');
  12359. if (this._caps.pvrtc)
  12360. this.texturesSupported.push('-pvrtc.ktx');
  12361. if (this._caps.etc2)
  12362. this.texturesSupported.push('-etc2.ktx');
  12363. if (this._caps.etc1)
  12364. this.texturesSupported.push('-etc1.ktx');
  12365. if (this._gl.getShaderPrecisionFormat) {
  12366. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12367. if (highp) {
  12368. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12369. }
  12370. }
  12371. // Depth buffer
  12372. this.setDepthBuffer(true);
  12373. this.setDepthFunctionToLessOrEqual();
  12374. this.setDepthWrite(true);
  12375. // Texture maps
  12376. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12377. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12378. this._nextFreeTextureSlots.push(slot);
  12379. }
  12380. };
  12381. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12382. /**
  12383. * Gets version of the current webGL context
  12384. */
  12385. get: function () {
  12386. return this._webGLVersion;
  12387. },
  12388. enumerable: true,
  12389. configurable: true
  12390. });
  12391. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12392. /**
  12393. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12394. */
  12395. get: function () {
  12396. return this._isStencilEnable;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. Engine.prototype._prepareWorkingCanvas = function () {
  12402. if (this._workingCanvas) {
  12403. return;
  12404. }
  12405. this._workingCanvas = document.createElement("canvas");
  12406. var context = this._workingCanvas.getContext("2d");
  12407. if (context) {
  12408. this._workingContext = context;
  12409. }
  12410. };
  12411. /**
  12412. * Reset the texture cache to empty state
  12413. */
  12414. Engine.prototype.resetTextureCache = function () {
  12415. for (var key in this._boundTexturesCache) {
  12416. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12417. continue;
  12418. }
  12419. var boundTexture = this._boundTexturesCache[key];
  12420. if (boundTexture) {
  12421. this._removeDesignatedSlot(boundTexture);
  12422. }
  12423. this._boundTexturesCache[key] = null;
  12424. }
  12425. if (!this.disableTextureBindingOptimization) {
  12426. this._nextFreeTextureSlots = [];
  12427. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12428. this._nextFreeTextureSlots.push(slot);
  12429. }
  12430. }
  12431. this._currentTextureChannel = -1;
  12432. };
  12433. /**
  12434. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12435. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12436. * @returns true if engine is in deterministic lock step mode
  12437. */
  12438. Engine.prototype.isDeterministicLockStep = function () {
  12439. return this._deterministicLockstep;
  12440. };
  12441. /**
  12442. * Gets the max steps when engine is running in deterministic lock step
  12443. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12444. * @returns the max steps
  12445. */
  12446. Engine.prototype.getLockstepMaxSteps = function () {
  12447. return this._lockstepMaxSteps;
  12448. };
  12449. /**
  12450. * Gets an object containing information about the current webGL context
  12451. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12452. */
  12453. Engine.prototype.getGlInfo = function () {
  12454. return {
  12455. vendor: this._glVendor,
  12456. renderer: this._glRenderer,
  12457. version: this._glVersion
  12458. };
  12459. };
  12460. /**
  12461. * Gets current aspect ratio
  12462. * @param camera defines the camera to use to get the aspect ratio
  12463. * @param useScreen defines if screen size must be used (or the current render target if any)
  12464. * @returns a number defining the aspect ratio
  12465. */
  12466. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12467. if (useScreen === void 0) { useScreen = false; }
  12468. var viewport = camera.viewport;
  12469. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12470. };
  12471. /**
  12472. * Gets current screen aspect ratio
  12473. * @returns a number defining the aspect ratio
  12474. */
  12475. Engine.prototype.getScreenAspectRatio = function () {
  12476. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12477. };
  12478. /**
  12479. * Gets the current render width
  12480. * @param useScreen defines if screen size must be used (or the current render target if any)
  12481. * @returns a number defining the current render width
  12482. */
  12483. Engine.prototype.getRenderWidth = function (useScreen) {
  12484. if (useScreen === void 0) { useScreen = false; }
  12485. if (!useScreen && this._currentRenderTarget) {
  12486. return this._currentRenderTarget.width;
  12487. }
  12488. return this._gl.drawingBufferWidth;
  12489. };
  12490. /**
  12491. * Gets the current render height
  12492. * @param useScreen defines if screen size must be used (or the current render target if any)
  12493. * @returns a number defining the current render height
  12494. */
  12495. Engine.prototype.getRenderHeight = function (useScreen) {
  12496. if (useScreen === void 0) { useScreen = false; }
  12497. if (!useScreen && this._currentRenderTarget) {
  12498. return this._currentRenderTarget.height;
  12499. }
  12500. return this._gl.drawingBufferHeight;
  12501. };
  12502. /**
  12503. * Gets the HTML canvas attached with the current webGL context
  12504. * @returns a HTML canvas
  12505. */
  12506. Engine.prototype.getRenderingCanvas = function () {
  12507. return this._renderingCanvas;
  12508. };
  12509. /**
  12510. * Gets the client rect of the HTML canvas attached with the current webGL context
  12511. * @returns a client rectanglee
  12512. */
  12513. Engine.prototype.getRenderingCanvasClientRect = function () {
  12514. if (!this._renderingCanvas) {
  12515. return null;
  12516. }
  12517. return this._renderingCanvas.getBoundingClientRect();
  12518. };
  12519. /**
  12520. * Defines the hardware scaling level.
  12521. * By default the hardware scaling level is computed from the window device ratio.
  12522. * 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.
  12523. * @param level defines the level to use
  12524. */
  12525. Engine.prototype.setHardwareScalingLevel = function (level) {
  12526. this._hardwareScalingLevel = level;
  12527. this.resize();
  12528. };
  12529. /**
  12530. * Gets the current hardware scaling level.
  12531. * By default the hardware scaling level is computed from the window device ratio.
  12532. * 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.
  12533. * @returns a number indicating the current hardware scaling level
  12534. */
  12535. Engine.prototype.getHardwareScalingLevel = function () {
  12536. return this._hardwareScalingLevel;
  12537. };
  12538. /**
  12539. * Gets the list of loaded textures
  12540. * @returns an array containing all loaded textures
  12541. */
  12542. Engine.prototype.getLoadedTexturesCache = function () {
  12543. return this._internalTexturesCache;
  12544. };
  12545. /**
  12546. * Gets the object containing all engine capabilities
  12547. * @returns the EngineCapabilities object
  12548. */
  12549. Engine.prototype.getCaps = function () {
  12550. return this._caps;
  12551. };
  12552. Object.defineProperty(Engine.prototype, "drawCalls", {
  12553. /** @hidden */
  12554. get: function () {
  12555. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12556. return 0;
  12557. },
  12558. enumerable: true,
  12559. configurable: true
  12560. });
  12561. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12562. /** @hidden */
  12563. get: function () {
  12564. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12565. return null;
  12566. },
  12567. enumerable: true,
  12568. configurable: true
  12569. });
  12570. /**
  12571. * Gets the current depth function
  12572. * @returns a number defining the depth function
  12573. */
  12574. Engine.prototype.getDepthFunction = function () {
  12575. return this._depthCullingState.depthFunc;
  12576. };
  12577. /**
  12578. * Sets the current depth function
  12579. * @param depthFunc defines the function to use
  12580. */
  12581. Engine.prototype.setDepthFunction = function (depthFunc) {
  12582. this._depthCullingState.depthFunc = depthFunc;
  12583. };
  12584. /**
  12585. * Sets the current depth function to GREATER
  12586. */
  12587. Engine.prototype.setDepthFunctionToGreater = function () {
  12588. this._depthCullingState.depthFunc = this._gl.GREATER;
  12589. };
  12590. /**
  12591. * Sets the current depth function to GEQUAL
  12592. */
  12593. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12594. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12595. };
  12596. /**
  12597. * Sets the current depth function to LESS
  12598. */
  12599. Engine.prototype.setDepthFunctionToLess = function () {
  12600. this._depthCullingState.depthFunc = this._gl.LESS;
  12601. };
  12602. /**
  12603. * Sets the current depth function to LEQUAL
  12604. */
  12605. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12606. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12607. };
  12608. /**
  12609. * Gets a boolean indicating if stencil buffer is enabled
  12610. * @returns the current stencil buffer state
  12611. */
  12612. Engine.prototype.getStencilBuffer = function () {
  12613. return this._stencilState.stencilTest;
  12614. };
  12615. /**
  12616. * Enable or disable the stencil buffer
  12617. * @param enable defines if the stencil buffer must be enabled or disabled
  12618. */
  12619. Engine.prototype.setStencilBuffer = function (enable) {
  12620. this._stencilState.stencilTest = enable;
  12621. };
  12622. /**
  12623. * Gets the current stencil mask
  12624. * @returns a number defining the new stencil mask to use
  12625. */
  12626. Engine.prototype.getStencilMask = function () {
  12627. return this._stencilState.stencilMask;
  12628. };
  12629. /**
  12630. * Sets the current stencil mask
  12631. * @param mask defines the new stencil mask to use
  12632. */
  12633. Engine.prototype.setStencilMask = function (mask) {
  12634. this._stencilState.stencilMask = mask;
  12635. };
  12636. /**
  12637. * Gets the current stencil function
  12638. * @returns a number defining the stencil function to use
  12639. */
  12640. Engine.prototype.getStencilFunction = function () {
  12641. return this._stencilState.stencilFunc;
  12642. };
  12643. /**
  12644. * Gets the current stencil reference value
  12645. * @returns a number defining the stencil reference value to use
  12646. */
  12647. Engine.prototype.getStencilFunctionReference = function () {
  12648. return this._stencilState.stencilFuncRef;
  12649. };
  12650. /**
  12651. * Gets the current stencil mask
  12652. * @returns a number defining the stencil mask to use
  12653. */
  12654. Engine.prototype.getStencilFunctionMask = function () {
  12655. return this._stencilState.stencilFuncMask;
  12656. };
  12657. /**
  12658. * Sets the current stencil function
  12659. * @param stencilFunc defines the new stencil function to use
  12660. */
  12661. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12662. this._stencilState.stencilFunc = stencilFunc;
  12663. };
  12664. /**
  12665. * Sets the current stencil reference
  12666. * @param reference defines the new stencil reference to use
  12667. */
  12668. Engine.prototype.setStencilFunctionReference = function (reference) {
  12669. this._stencilState.stencilFuncRef = reference;
  12670. };
  12671. /**
  12672. * Sets the current stencil mask
  12673. * @param mask defines the new stencil mask to use
  12674. */
  12675. Engine.prototype.setStencilFunctionMask = function (mask) {
  12676. this._stencilState.stencilFuncMask = mask;
  12677. };
  12678. /**
  12679. * Gets the current stencil operation when stencil fails
  12680. * @returns a number defining stencil operation to use when stencil fails
  12681. */
  12682. Engine.prototype.getStencilOperationFail = function () {
  12683. return this._stencilState.stencilOpStencilFail;
  12684. };
  12685. /**
  12686. * Gets the current stencil operation when depth fails
  12687. * @returns a number defining stencil operation to use when depth fails
  12688. */
  12689. Engine.prototype.getStencilOperationDepthFail = function () {
  12690. return this._stencilState.stencilOpDepthFail;
  12691. };
  12692. /**
  12693. * Gets the current stencil operation when stencil passes
  12694. * @returns a number defining stencil operation to use when stencil passes
  12695. */
  12696. Engine.prototype.getStencilOperationPass = function () {
  12697. return this._stencilState.stencilOpStencilDepthPass;
  12698. };
  12699. /**
  12700. * Sets the stencil operation to use when stencil fails
  12701. * @param operation defines the stencil operation to use when stencil fails
  12702. */
  12703. Engine.prototype.setStencilOperationFail = function (operation) {
  12704. this._stencilState.stencilOpStencilFail = operation;
  12705. };
  12706. /**
  12707. * Sets the stencil operation to use when depth fails
  12708. * @param operation defines the stencil operation to use when depth fails
  12709. */
  12710. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12711. this._stencilState.stencilOpDepthFail = operation;
  12712. };
  12713. /**
  12714. * Sets the stencil operation to use when stencil passes
  12715. * @param operation defines the stencil operation to use when stencil passes
  12716. */
  12717. Engine.prototype.setStencilOperationPass = function (operation) {
  12718. this._stencilState.stencilOpStencilDepthPass = operation;
  12719. };
  12720. /**
  12721. * Sets a boolean indicating if the dithering state is enabled or disabled
  12722. * @param value defines the dithering state
  12723. */
  12724. Engine.prototype.setDitheringState = function (value) {
  12725. if (value) {
  12726. this._gl.enable(this._gl.DITHER);
  12727. }
  12728. else {
  12729. this._gl.disable(this._gl.DITHER);
  12730. }
  12731. };
  12732. /**
  12733. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12734. * @param value defines the rasterizer state
  12735. */
  12736. Engine.prototype.setRasterizerState = function (value) {
  12737. if (value) {
  12738. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12739. }
  12740. else {
  12741. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12742. }
  12743. };
  12744. /**
  12745. * stop executing a render loop function and remove it from the execution array
  12746. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12747. */
  12748. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12749. if (!renderFunction) {
  12750. this._activeRenderLoops = [];
  12751. return;
  12752. }
  12753. var index = this._activeRenderLoops.indexOf(renderFunction);
  12754. if (index >= 0) {
  12755. this._activeRenderLoops.splice(index, 1);
  12756. }
  12757. };
  12758. /** @hidden */
  12759. Engine.prototype._renderLoop = function () {
  12760. if (!this._contextWasLost) {
  12761. var shouldRender = true;
  12762. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12763. shouldRender = false;
  12764. }
  12765. if (shouldRender) {
  12766. // Start new frame
  12767. this.beginFrame();
  12768. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12769. var renderFunction = this._activeRenderLoops[index];
  12770. renderFunction();
  12771. }
  12772. // Present
  12773. this.endFrame();
  12774. }
  12775. }
  12776. if (this._activeRenderLoops.length > 0) {
  12777. // Register new frame
  12778. var requester = null;
  12779. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12780. requester = this._vrDisplay;
  12781. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12782. }
  12783. else {
  12784. this._renderingQueueLaunched = false;
  12785. }
  12786. };
  12787. /**
  12788. * Register and execute a render loop. The engine can have more than one render function
  12789. * @param renderFunction defines the function to continuously execute
  12790. */
  12791. Engine.prototype.runRenderLoop = function (renderFunction) {
  12792. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12793. return;
  12794. }
  12795. this._activeRenderLoops.push(renderFunction);
  12796. if (!this._renderingQueueLaunched) {
  12797. this._renderingQueueLaunched = true;
  12798. this._bindedRenderFunction = this._renderLoop.bind(this);
  12799. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12800. }
  12801. };
  12802. /**
  12803. * Toggle full screen mode
  12804. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12805. * @param options defines an option object to be sent to the requestFullscreen function
  12806. */
  12807. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12808. if (this.isFullscreen) {
  12809. BABYLON.Tools.ExitFullscreen();
  12810. }
  12811. else {
  12812. this._pointerLockRequested = requestPointerLock;
  12813. if (this._renderingCanvas) {
  12814. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12815. }
  12816. }
  12817. };
  12818. /**
  12819. * Clear the current render buffer or the current render target (if any is set up)
  12820. * @param color defines the color to use
  12821. * @param backBuffer defines if the back buffer must be cleared
  12822. * @param depth defines if the depth buffer must be cleared
  12823. * @param stencil defines if the stencil buffer must be cleared
  12824. */
  12825. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12826. if (stencil === void 0) { stencil = false; }
  12827. this.applyStates();
  12828. var mode = 0;
  12829. if (backBuffer && color) {
  12830. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12831. mode |= this._gl.COLOR_BUFFER_BIT;
  12832. }
  12833. if (depth) {
  12834. this._gl.clearDepth(1.0);
  12835. mode |= this._gl.DEPTH_BUFFER_BIT;
  12836. }
  12837. if (stencil) {
  12838. this._gl.clearStencil(0);
  12839. mode |= this._gl.STENCIL_BUFFER_BIT;
  12840. }
  12841. this._gl.clear(mode);
  12842. };
  12843. /**
  12844. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12845. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12846. * @param y defines the y-coordinate of the corner of the clear rectangle
  12847. * @param width defines the width of the clear rectangle
  12848. * @param height defines the height of the clear rectangle
  12849. * @param clearColor defines the clear color
  12850. */
  12851. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12852. var gl = this._gl;
  12853. // Save state
  12854. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12855. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12856. // Change state
  12857. gl.enable(gl.SCISSOR_TEST);
  12858. gl.scissor(x, y, width, height);
  12859. // Clear
  12860. this.clear(clearColor, true, true, true);
  12861. // Restore state
  12862. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12863. if (curScissor === true) {
  12864. gl.enable(gl.SCISSOR_TEST);
  12865. }
  12866. else {
  12867. gl.disable(gl.SCISSOR_TEST);
  12868. }
  12869. };
  12870. /** @hidden */
  12871. Engine.prototype._viewport = function (x, y, width, height) {
  12872. if (x !== this._viewportCached.x ||
  12873. y !== this._viewportCached.y ||
  12874. width !== this._viewportCached.z ||
  12875. height !== this._viewportCached.w) {
  12876. this._viewportCached.x = x;
  12877. this._viewportCached.y = y;
  12878. this._viewportCached.z = width;
  12879. this._viewportCached.w = height;
  12880. this._gl.viewport(x, y, width, height);
  12881. }
  12882. };
  12883. /**
  12884. * Set the WebGL's viewport
  12885. * @param viewport defines the viewport element to be used
  12886. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12887. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12888. */
  12889. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12890. var width = requiredWidth || this.getRenderWidth();
  12891. var height = requiredHeight || this.getRenderHeight();
  12892. var x = viewport.x || 0;
  12893. var y = viewport.y || 0;
  12894. this._cachedViewport = viewport;
  12895. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12896. };
  12897. /**
  12898. * Directly set the WebGL Viewport
  12899. * @param x defines the x coordinate of the viewport (in screen space)
  12900. * @param y defines the y coordinate of the viewport (in screen space)
  12901. * @param width defines the width of the viewport (in screen space)
  12902. * @param height defines the height of the viewport (in screen space)
  12903. * @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
  12904. */
  12905. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12906. var currentViewport = this._cachedViewport;
  12907. this._cachedViewport = null;
  12908. this._viewport(x, y, width, height);
  12909. return currentViewport;
  12910. };
  12911. /**
  12912. * Begin a new frame
  12913. */
  12914. Engine.prototype.beginFrame = function () {
  12915. this.onBeginFrameObservable.notifyObservers(this);
  12916. this._measureFps();
  12917. };
  12918. /**
  12919. * Enf the current frame
  12920. */
  12921. Engine.prototype.endFrame = function () {
  12922. // Force a flush in case we are using a bad OS.
  12923. if (this._badOS) {
  12924. this.flushFramebuffer();
  12925. }
  12926. // Submit frame to the vr device, if enabled
  12927. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12928. // TODO: We should only submit the frame if we read frameData successfully.
  12929. this._vrDisplay.submitFrame();
  12930. }
  12931. this.onEndFrameObservable.notifyObservers(this);
  12932. };
  12933. /**
  12934. * Resize the view according to the canvas' size
  12935. */
  12936. Engine.prototype.resize = function () {
  12937. // We're not resizing the size of the canvas while in VR mode & presenting
  12938. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12939. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12940. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12941. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12942. }
  12943. };
  12944. /**
  12945. * Force a specific size of the canvas
  12946. * @param width defines the new canvas' width
  12947. * @param height defines the new canvas' height
  12948. */
  12949. Engine.prototype.setSize = function (width, height) {
  12950. if (!this._renderingCanvas) {
  12951. return;
  12952. }
  12953. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12954. return;
  12955. }
  12956. this._renderingCanvas.width = width;
  12957. this._renderingCanvas.height = height;
  12958. for (var index = 0; index < this.scenes.length; index++) {
  12959. var scene = this.scenes[index];
  12960. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12961. var cam = scene.cameras[camIndex];
  12962. cam._currentRenderId = 0;
  12963. }
  12964. }
  12965. if (this.onResizeObservable.hasObservers) {
  12966. this.onResizeObservable.notifyObservers(this);
  12967. }
  12968. };
  12969. // WebVR functions
  12970. /**
  12971. * Gets a boolean indicating if a webVR device was detected
  12972. * @returns true if a webVR device was detected
  12973. */
  12974. Engine.prototype.isVRDevicePresent = function () {
  12975. return !!this._vrDisplay;
  12976. };
  12977. /**
  12978. * Gets the current webVR device
  12979. * @returns the current webVR device (or null)
  12980. */
  12981. Engine.prototype.getVRDevice = function () {
  12982. return this._vrDisplay;
  12983. };
  12984. /**
  12985. * Initializes a webVR display and starts listening to display change events
  12986. * The onVRDisplayChangedObservable will be notified upon these changes
  12987. * @returns The onVRDisplayChangedObservable
  12988. */
  12989. Engine.prototype.initWebVR = function () {
  12990. this.initWebVRAsync();
  12991. return this.onVRDisplayChangedObservable;
  12992. };
  12993. /**
  12994. * Initializes a webVR display and starts listening to display change events
  12995. * The onVRDisplayChangedObservable will be notified upon these changes
  12996. * @returns A promise containing a VRDisplay and if vr is supported
  12997. */
  12998. Engine.prototype.initWebVRAsync = function () {
  12999. var _this = this;
  13000. var notifyObservers = function () {
  13001. var eventArgs = {
  13002. vrDisplay: _this._vrDisplay,
  13003. vrSupported: _this._vrSupported
  13004. };
  13005. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13006. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13007. };
  13008. if (!this._onVrDisplayConnect) {
  13009. this._onVrDisplayConnect = function (event) {
  13010. _this._vrDisplay = event.display;
  13011. notifyObservers();
  13012. };
  13013. this._onVrDisplayDisconnect = function () {
  13014. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13015. _this._vrDisplay = undefined;
  13016. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13017. notifyObservers();
  13018. };
  13019. this._onVrDisplayPresentChange = function () {
  13020. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13021. };
  13022. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13023. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13024. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13025. }
  13026. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13027. this._webVRInitPromise.then(notifyObservers);
  13028. return this._webVRInitPromise;
  13029. };
  13030. /**
  13031. * Call this function to switch to webVR mode
  13032. * Will do nothing if webVR is not supported or if there is no webVR device
  13033. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13034. */
  13035. Engine.prototype.enableVR = function () {
  13036. var _this = this;
  13037. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13038. var onResolved = function () {
  13039. _this.onVRRequestPresentComplete.notifyObservers(true);
  13040. _this._onVRFullScreenTriggered();
  13041. };
  13042. var onRejected = function () {
  13043. _this.onVRRequestPresentComplete.notifyObservers(false);
  13044. };
  13045. this.onVRRequestPresentStart.notifyObservers(this);
  13046. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13047. }
  13048. };
  13049. /**
  13050. * Call this function to leave webVR mode
  13051. * Will do nothing if webVR is not supported or if there is no webVR device
  13052. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13053. */
  13054. Engine.prototype.disableVR = function () {
  13055. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13056. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13057. }
  13058. };
  13059. Engine.prototype._getVRDisplaysAsync = function () {
  13060. var _this = this;
  13061. return new Promise(function (res, rej) {
  13062. if (navigator.getVRDisplays) {
  13063. navigator.getVRDisplays().then(function (devices) {
  13064. _this._vrSupported = true;
  13065. // note that devices may actually be an empty array. This is fine;
  13066. // we expect this._vrDisplay to be undefined in this case.
  13067. _this._vrDisplay = devices[0];
  13068. res({
  13069. vrDisplay: _this._vrDisplay,
  13070. vrSupported: _this._vrSupported
  13071. });
  13072. });
  13073. }
  13074. else {
  13075. _this._vrDisplay = undefined;
  13076. _this._vrSupported = false;
  13077. res({
  13078. vrDisplay: _this._vrDisplay,
  13079. vrSupported: _this._vrSupported
  13080. });
  13081. }
  13082. });
  13083. };
  13084. /**
  13085. * Binds the frame buffer to the specified texture.
  13086. * @param texture The texture to render to or null for the default canvas
  13087. * @param faceIndex The face of the texture to render to in case of cube texture
  13088. * @param requiredWidth The width of the target to render to
  13089. * @param requiredHeight The height of the target to render to
  13090. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13091. * @param depthStencilTexture The depth stencil texture to use to render
  13092. * @param lodLevel defines le lod level to bind to the frame buffer
  13093. */
  13094. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13095. if (lodLevel === void 0) { lodLevel = 0; }
  13096. if (this._currentRenderTarget) {
  13097. this.unBindFramebuffer(this._currentRenderTarget);
  13098. }
  13099. this._currentRenderTarget = texture;
  13100. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13101. var gl = this._gl;
  13102. if (texture.isCube) {
  13103. if (faceIndex === undefined) {
  13104. faceIndex = 0;
  13105. }
  13106. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13107. if (depthStencilTexture) {
  13108. if (depthStencilTexture._generateStencilBuffer) {
  13109. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13110. }
  13111. else {
  13112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13113. }
  13114. }
  13115. }
  13116. if (this._cachedViewport && !forceFullscreenViewport) {
  13117. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13118. }
  13119. else {
  13120. if (!requiredWidth) {
  13121. requiredWidth = texture.width;
  13122. if (lodLevel) {
  13123. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13124. }
  13125. }
  13126. if (!requiredHeight) {
  13127. requiredHeight = texture.height;
  13128. if (lodLevel) {
  13129. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13130. }
  13131. }
  13132. this._viewport(0, 0, requiredWidth, requiredHeight);
  13133. }
  13134. this.wipeCaches();
  13135. };
  13136. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13137. if (this._currentFramebuffer !== framebuffer) {
  13138. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13139. this._currentFramebuffer = framebuffer;
  13140. }
  13141. };
  13142. /**
  13143. * Unbind the current render target texture from the webGL context
  13144. * @param texture defines the render target texture to unbind
  13145. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13146. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13147. */
  13148. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13149. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13150. this._currentRenderTarget = null;
  13151. // If MSAA, we need to bitblt back to main texture
  13152. var gl = this._gl;
  13153. if (texture._MSAAFramebuffer) {
  13154. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13155. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13156. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13157. }
  13158. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13159. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13160. gl.generateMipmap(gl.TEXTURE_2D);
  13161. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13162. }
  13163. if (onBeforeUnbind) {
  13164. if (texture._MSAAFramebuffer) {
  13165. // Bind the correct framebuffer
  13166. this.bindUnboundFramebuffer(texture._framebuffer);
  13167. }
  13168. onBeforeUnbind();
  13169. }
  13170. this.bindUnboundFramebuffer(null);
  13171. };
  13172. /**
  13173. * Unbind a list of render target textures from the webGL context
  13174. * This is used only when drawBuffer extension or webGL2 are active
  13175. * @param textures defines the render target textures to unbind
  13176. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13177. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13178. */
  13179. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13180. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13181. this._currentRenderTarget = null;
  13182. // If MSAA, we need to bitblt back to main texture
  13183. var gl = this._gl;
  13184. if (textures[0]._MSAAFramebuffer) {
  13185. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13186. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13187. var attachments = textures[0]._attachments;
  13188. if (!attachments) {
  13189. attachments = new Array(textures.length);
  13190. textures[0]._attachments = attachments;
  13191. }
  13192. for (var i = 0; i < textures.length; i++) {
  13193. var texture = textures[i];
  13194. for (var j = 0; j < attachments.length; j++) {
  13195. attachments[j] = gl.NONE;
  13196. }
  13197. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13198. gl.readBuffer(attachments[i]);
  13199. gl.drawBuffers(attachments);
  13200. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13201. }
  13202. for (var i = 0; i < attachments.length; i++) {
  13203. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13204. }
  13205. gl.drawBuffers(attachments);
  13206. }
  13207. for (var i = 0; i < textures.length; i++) {
  13208. var texture = textures[i];
  13209. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13210. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13211. gl.generateMipmap(gl.TEXTURE_2D);
  13212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13213. }
  13214. }
  13215. if (onBeforeUnbind) {
  13216. if (textures[0]._MSAAFramebuffer) {
  13217. // Bind the correct framebuffer
  13218. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13219. }
  13220. onBeforeUnbind();
  13221. }
  13222. this.bindUnboundFramebuffer(null);
  13223. };
  13224. /**
  13225. * Force the mipmap generation for the given render target texture
  13226. * @param texture defines the render target texture to use
  13227. */
  13228. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13229. if (texture.generateMipMaps) {
  13230. var gl = this._gl;
  13231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13232. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13233. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13234. }
  13235. };
  13236. /**
  13237. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13238. */
  13239. Engine.prototype.flushFramebuffer = function () {
  13240. this._gl.flush();
  13241. };
  13242. /**
  13243. * Unbind the current render target and bind the default framebuffer
  13244. */
  13245. Engine.prototype.restoreDefaultFramebuffer = function () {
  13246. if (this._currentRenderTarget) {
  13247. this.unBindFramebuffer(this._currentRenderTarget);
  13248. }
  13249. else {
  13250. this.bindUnboundFramebuffer(null);
  13251. }
  13252. if (this._cachedViewport) {
  13253. this.setViewport(this._cachedViewport);
  13254. }
  13255. this.wipeCaches();
  13256. };
  13257. // UBOs
  13258. /**
  13259. * Create an uniform buffer
  13260. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13261. * @param elements defines the content of the uniform buffer
  13262. * @returns the webGL uniform buffer
  13263. */
  13264. Engine.prototype.createUniformBuffer = function (elements) {
  13265. var ubo = this._gl.createBuffer();
  13266. if (!ubo) {
  13267. throw new Error("Unable to create uniform buffer");
  13268. }
  13269. this.bindUniformBuffer(ubo);
  13270. if (elements instanceof Float32Array) {
  13271. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13272. }
  13273. else {
  13274. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13275. }
  13276. this.bindUniformBuffer(null);
  13277. ubo.references = 1;
  13278. return ubo;
  13279. };
  13280. /**
  13281. * Create a dynamic uniform buffer
  13282. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13283. * @param elements defines the content of the uniform buffer
  13284. * @returns the webGL uniform buffer
  13285. */
  13286. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13287. var ubo = this._gl.createBuffer();
  13288. if (!ubo) {
  13289. throw new Error("Unable to create dynamic uniform buffer");
  13290. }
  13291. this.bindUniformBuffer(ubo);
  13292. if (elements instanceof Float32Array) {
  13293. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13294. }
  13295. else {
  13296. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13297. }
  13298. this.bindUniformBuffer(null);
  13299. ubo.references = 1;
  13300. return ubo;
  13301. };
  13302. /**
  13303. * Update an existing uniform buffer
  13304. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13305. * @param uniformBuffer defines the target uniform buffer
  13306. * @param elements defines the content to update
  13307. * @param offset defines the offset in the uniform buffer where update should start
  13308. * @param count defines the size of the data to update
  13309. */
  13310. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13311. this.bindUniformBuffer(uniformBuffer);
  13312. if (offset === undefined) {
  13313. offset = 0;
  13314. }
  13315. if (count === undefined) {
  13316. if (elements instanceof Float32Array) {
  13317. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13318. }
  13319. else {
  13320. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13321. }
  13322. }
  13323. else {
  13324. if (elements instanceof Float32Array) {
  13325. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13326. }
  13327. else {
  13328. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13329. }
  13330. }
  13331. this.bindUniformBuffer(null);
  13332. };
  13333. // VBOs
  13334. Engine.prototype._resetVertexBufferBinding = function () {
  13335. this.bindArrayBuffer(null);
  13336. this._cachedVertexBuffers = null;
  13337. };
  13338. /**
  13339. * Creates a vertex buffer
  13340. * @param data the data for the vertex buffer
  13341. * @returns the new WebGL static buffer
  13342. */
  13343. Engine.prototype.createVertexBuffer = function (data) {
  13344. var vbo = this._gl.createBuffer();
  13345. if (!vbo) {
  13346. throw new Error("Unable to create vertex buffer");
  13347. }
  13348. this.bindArrayBuffer(vbo);
  13349. if (data instanceof Array) {
  13350. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13351. }
  13352. else {
  13353. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13354. }
  13355. this._resetVertexBufferBinding();
  13356. vbo.references = 1;
  13357. return vbo;
  13358. };
  13359. /**
  13360. * Creates a dynamic vertex buffer
  13361. * @param data the data for the dynamic vertex buffer
  13362. * @returns the new WebGL dynamic buffer
  13363. */
  13364. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13365. var vbo = this._gl.createBuffer();
  13366. if (!vbo) {
  13367. throw new Error("Unable to create dynamic vertex buffer");
  13368. }
  13369. this.bindArrayBuffer(vbo);
  13370. if (data instanceof Array) {
  13371. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13372. }
  13373. else {
  13374. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13375. }
  13376. this._resetVertexBufferBinding();
  13377. vbo.references = 1;
  13378. return vbo;
  13379. };
  13380. /**
  13381. * Update a dynamic index buffer
  13382. * @param indexBuffer defines the target index buffer
  13383. * @param indices defines the data to update
  13384. * @param offset defines the offset in the target index buffer where update should start
  13385. */
  13386. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13387. if (offset === void 0) { offset = 0; }
  13388. // Force cache update
  13389. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13390. this.bindIndexBuffer(indexBuffer);
  13391. var arrayBuffer;
  13392. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13393. arrayBuffer = indices;
  13394. }
  13395. else {
  13396. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13397. }
  13398. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13399. this._resetIndexBufferBinding();
  13400. };
  13401. /**
  13402. * Updates a dynamic vertex buffer.
  13403. * @param vertexBuffer the vertex buffer to update
  13404. * @param data the data used to update the vertex buffer
  13405. * @param byteOffset the byte offset of the data
  13406. * @param byteLength the byte length of the data
  13407. */
  13408. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13409. this.bindArrayBuffer(vertexBuffer);
  13410. if (byteOffset === undefined) {
  13411. byteOffset = 0;
  13412. }
  13413. if (byteLength === undefined) {
  13414. if (data instanceof Array) {
  13415. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13416. }
  13417. else {
  13418. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13419. }
  13420. }
  13421. else {
  13422. if (data instanceof Array) {
  13423. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13424. }
  13425. else {
  13426. if (data instanceof ArrayBuffer) {
  13427. data = new Uint8Array(data, byteOffset, byteLength);
  13428. }
  13429. else {
  13430. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13431. }
  13432. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13433. }
  13434. }
  13435. this._resetVertexBufferBinding();
  13436. };
  13437. Engine.prototype._resetIndexBufferBinding = function () {
  13438. this.bindIndexBuffer(null);
  13439. this._cachedIndexBuffer = null;
  13440. };
  13441. /**
  13442. * Creates a new index buffer
  13443. * @param indices defines the content of the index buffer
  13444. * @param updatable defines if the index buffer must be updatable
  13445. * @returns a new webGL buffer
  13446. */
  13447. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13448. var vbo = this._gl.createBuffer();
  13449. if (!vbo) {
  13450. throw new Error("Unable to create index buffer");
  13451. }
  13452. this.bindIndexBuffer(vbo);
  13453. // Check for 32 bits indices
  13454. var arrayBuffer;
  13455. var need32Bits = false;
  13456. if (indices instanceof Uint16Array) {
  13457. arrayBuffer = indices;
  13458. }
  13459. else {
  13460. //check 32 bit support
  13461. if (this._caps.uintIndices) {
  13462. if (indices instanceof Uint32Array) {
  13463. arrayBuffer = indices;
  13464. need32Bits = true;
  13465. }
  13466. else {
  13467. //number[] or Int32Array, check if 32 bit is necessary
  13468. for (var index = 0; index < indices.length; index++) {
  13469. if (indices[index] > 65535) {
  13470. need32Bits = true;
  13471. break;
  13472. }
  13473. }
  13474. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13475. }
  13476. }
  13477. else {
  13478. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13479. arrayBuffer = new Uint16Array(indices);
  13480. }
  13481. }
  13482. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13483. this._resetIndexBufferBinding();
  13484. vbo.references = 1;
  13485. vbo.is32Bits = need32Bits;
  13486. return vbo;
  13487. };
  13488. /**
  13489. * Bind a webGL buffer to the webGL context
  13490. * @param buffer defines the buffer to bind
  13491. */
  13492. Engine.prototype.bindArrayBuffer = function (buffer) {
  13493. if (!this._vaoRecordInProgress) {
  13494. this._unbindVertexArrayObject();
  13495. }
  13496. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13497. };
  13498. /**
  13499. * Bind an uniform buffer to the current webGL context
  13500. * @param buffer defines the buffer to bind
  13501. */
  13502. Engine.prototype.bindUniformBuffer = function (buffer) {
  13503. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13504. };
  13505. /**
  13506. * Bind a buffer to the current webGL context at a given location
  13507. * @param buffer defines the buffer to bind
  13508. * @param location defines the index where to bind the buffer
  13509. */
  13510. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13511. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13512. };
  13513. /**
  13514. * Bind a specific block at a given index in a specific shader program
  13515. * @param shaderProgram defines the shader program
  13516. * @param blockName defines the block name
  13517. * @param index defines the index where to bind the block
  13518. */
  13519. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13520. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13521. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13522. };
  13523. ;
  13524. Engine.prototype.bindIndexBuffer = function (buffer) {
  13525. if (!this._vaoRecordInProgress) {
  13526. this._unbindVertexArrayObject();
  13527. }
  13528. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13529. };
  13530. Engine.prototype.bindBuffer = function (buffer, target) {
  13531. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13532. this._gl.bindBuffer(target, buffer);
  13533. this._currentBoundBuffer[target] = buffer;
  13534. }
  13535. };
  13536. /**
  13537. * update the bound buffer with the given data
  13538. * @param data defines the data to update
  13539. */
  13540. Engine.prototype.updateArrayBuffer = function (data) {
  13541. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13542. };
  13543. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13544. var pointer = this._currentBufferPointers[indx];
  13545. var changed = false;
  13546. if (!pointer.active) {
  13547. changed = true;
  13548. pointer.active = true;
  13549. pointer.index = indx;
  13550. pointer.size = size;
  13551. pointer.type = type;
  13552. pointer.normalized = normalized;
  13553. pointer.stride = stride;
  13554. pointer.offset = offset;
  13555. pointer.buffer = buffer;
  13556. }
  13557. else {
  13558. if (pointer.buffer !== buffer) {
  13559. pointer.buffer = buffer;
  13560. changed = true;
  13561. }
  13562. if (pointer.size !== size) {
  13563. pointer.size = size;
  13564. changed = true;
  13565. }
  13566. if (pointer.type !== type) {
  13567. pointer.type = type;
  13568. changed = true;
  13569. }
  13570. if (pointer.normalized !== normalized) {
  13571. pointer.normalized = normalized;
  13572. changed = true;
  13573. }
  13574. if (pointer.stride !== stride) {
  13575. pointer.stride = stride;
  13576. changed = true;
  13577. }
  13578. if (pointer.offset !== offset) {
  13579. pointer.offset = offset;
  13580. changed = true;
  13581. }
  13582. }
  13583. if (changed || this._vaoRecordInProgress) {
  13584. this.bindArrayBuffer(buffer);
  13585. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13586. }
  13587. };
  13588. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13589. if (indexBuffer == null) {
  13590. return;
  13591. }
  13592. if (this._cachedIndexBuffer !== indexBuffer) {
  13593. this._cachedIndexBuffer = indexBuffer;
  13594. this.bindIndexBuffer(indexBuffer);
  13595. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13596. }
  13597. };
  13598. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13599. var attributes = effect.getAttributesNames();
  13600. if (!this._vaoRecordInProgress) {
  13601. this._unbindVertexArrayObject();
  13602. }
  13603. this.unbindAllAttributes();
  13604. for (var index = 0; index < attributes.length; index++) {
  13605. var order = effect.getAttributeLocation(index);
  13606. if (order >= 0) {
  13607. var vertexBuffer = vertexBuffers[attributes[index]];
  13608. if (!vertexBuffer) {
  13609. continue;
  13610. }
  13611. this._gl.enableVertexAttribArray(order);
  13612. if (!this._vaoRecordInProgress) {
  13613. this._vertexAttribArraysEnabled[order] = true;
  13614. }
  13615. var buffer = vertexBuffer.getBuffer();
  13616. if (buffer) {
  13617. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13618. if (vertexBuffer.getIsInstanced()) {
  13619. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13620. if (!this._vaoRecordInProgress) {
  13621. this._currentInstanceLocations.push(order);
  13622. this._currentInstanceBuffers.push(buffer);
  13623. }
  13624. }
  13625. }
  13626. }
  13627. }
  13628. };
  13629. /**
  13630. * Records a vertex array object
  13631. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13632. * @param vertexBuffers defines the list of vertex buffers to store
  13633. * @param indexBuffer defines the index buffer to store
  13634. * @param effect defines the effect to store
  13635. * @returns the new vertex array object
  13636. */
  13637. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13638. var vao = this._gl.createVertexArray();
  13639. this._vaoRecordInProgress = true;
  13640. this._gl.bindVertexArray(vao);
  13641. this._mustWipeVertexAttributes = true;
  13642. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13643. this.bindIndexBuffer(indexBuffer);
  13644. this._vaoRecordInProgress = false;
  13645. this._gl.bindVertexArray(null);
  13646. return vao;
  13647. };
  13648. /**
  13649. * Bind a specific vertex array object
  13650. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13651. * @param vertexArrayObject defines the vertex array object to bind
  13652. * @param indexBuffer defines the index buffer to bind
  13653. */
  13654. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13655. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13656. this._cachedVertexArrayObject = vertexArrayObject;
  13657. this._gl.bindVertexArray(vertexArrayObject);
  13658. this._cachedVertexBuffers = null;
  13659. this._cachedIndexBuffer = null;
  13660. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13661. this._mustWipeVertexAttributes = true;
  13662. }
  13663. };
  13664. /**
  13665. * Bind webGl buffers directly to the webGL context
  13666. * @param vertexBuffer defines the vertex buffer to bind
  13667. * @param indexBuffer defines the index buffer to bind
  13668. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13669. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13670. * @param effect defines the effect associated with the vertex buffer
  13671. */
  13672. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13673. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13674. this._cachedVertexBuffers = vertexBuffer;
  13675. this._cachedEffectForVertexBuffers = effect;
  13676. var attributesCount = effect.getAttributesCount();
  13677. this._unbindVertexArrayObject();
  13678. this.unbindAllAttributes();
  13679. var offset = 0;
  13680. for (var index = 0; index < attributesCount; index++) {
  13681. if (index < vertexDeclaration.length) {
  13682. var order = effect.getAttributeLocation(index);
  13683. if (order >= 0) {
  13684. this._gl.enableVertexAttribArray(order);
  13685. this._vertexAttribArraysEnabled[order] = true;
  13686. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13687. }
  13688. offset += vertexDeclaration[index] * 4;
  13689. }
  13690. }
  13691. }
  13692. this._bindIndexBufferWithCache(indexBuffer);
  13693. };
  13694. Engine.prototype._unbindVertexArrayObject = function () {
  13695. if (!this._cachedVertexArrayObject) {
  13696. return;
  13697. }
  13698. this._cachedVertexArrayObject = null;
  13699. this._gl.bindVertexArray(null);
  13700. };
  13701. /**
  13702. * Bind a list of vertex buffers to the webGL context
  13703. * @param vertexBuffers defines the list of vertex buffers to bind
  13704. * @param indexBuffer defines the index buffer to bind
  13705. * @param effect defines the effect associated with the vertex buffers
  13706. */
  13707. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13708. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13709. this._cachedVertexBuffers = vertexBuffers;
  13710. this._cachedEffectForVertexBuffers = effect;
  13711. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13712. }
  13713. this._bindIndexBufferWithCache(indexBuffer);
  13714. };
  13715. /**
  13716. * Unbind all instance attributes
  13717. */
  13718. Engine.prototype.unbindInstanceAttributes = function () {
  13719. var boundBuffer;
  13720. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13721. var instancesBuffer = this._currentInstanceBuffers[i];
  13722. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13723. boundBuffer = instancesBuffer;
  13724. this.bindArrayBuffer(instancesBuffer);
  13725. }
  13726. var offsetLocation = this._currentInstanceLocations[i];
  13727. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13728. }
  13729. this._currentInstanceBuffers.length = 0;
  13730. this._currentInstanceLocations.length = 0;
  13731. };
  13732. /**
  13733. * Release and free the memory of a vertex array object
  13734. * @param vao defines the vertex array object to delete
  13735. */
  13736. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13737. this._gl.deleteVertexArray(vao);
  13738. };
  13739. /** @hidden */
  13740. Engine.prototype._releaseBuffer = function (buffer) {
  13741. buffer.references--;
  13742. if (buffer.references === 0) {
  13743. this._gl.deleteBuffer(buffer);
  13744. return true;
  13745. }
  13746. return false;
  13747. };
  13748. /**
  13749. * Creates a webGL buffer to use with instanciation
  13750. * @param capacity defines the size of the buffer
  13751. * @returns the webGL buffer
  13752. */
  13753. Engine.prototype.createInstancesBuffer = function (capacity) {
  13754. var buffer = this._gl.createBuffer();
  13755. if (!buffer) {
  13756. throw new Error("Unable to create instance buffer");
  13757. }
  13758. buffer.capacity = capacity;
  13759. this.bindArrayBuffer(buffer);
  13760. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13761. return buffer;
  13762. };
  13763. /**
  13764. * Delete a webGL buffer used with instanciation
  13765. * @param buffer defines the webGL buffer to delete
  13766. */
  13767. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13768. this._gl.deleteBuffer(buffer);
  13769. };
  13770. /**
  13771. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13772. * @param instancesBuffer defines the webGL buffer to update and bind
  13773. * @param data defines the data to store in the buffer
  13774. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13775. */
  13776. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13777. this.bindArrayBuffer(instancesBuffer);
  13778. if (data) {
  13779. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13780. }
  13781. if (offsetLocations[0].index !== undefined) {
  13782. var stride = 0;
  13783. for (var i = 0; i < offsetLocations.length; i++) {
  13784. var ai = offsetLocations[i];
  13785. stride += ai.attributeSize * 4;
  13786. }
  13787. for (var i = 0; i < offsetLocations.length; i++) {
  13788. var ai = offsetLocations[i];
  13789. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13790. this._gl.enableVertexAttribArray(ai.index);
  13791. this._vertexAttribArraysEnabled[ai.index] = true;
  13792. }
  13793. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13794. this._gl.vertexAttribDivisor(ai.index, 1);
  13795. this._currentInstanceLocations.push(ai.index);
  13796. this._currentInstanceBuffers.push(instancesBuffer);
  13797. }
  13798. }
  13799. else {
  13800. for (var index = 0; index < 4; index++) {
  13801. var offsetLocation = offsetLocations[index];
  13802. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13803. this._gl.enableVertexAttribArray(offsetLocation);
  13804. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13805. }
  13806. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13807. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13808. this._currentInstanceLocations.push(offsetLocation);
  13809. this._currentInstanceBuffers.push(instancesBuffer);
  13810. }
  13811. }
  13812. };
  13813. /**
  13814. * Apply all cached states (depth, culling, stencil and alpha)
  13815. */
  13816. Engine.prototype.applyStates = function () {
  13817. this._depthCullingState.apply(this._gl);
  13818. this._stencilState.apply(this._gl);
  13819. this._alphaState.apply(this._gl);
  13820. };
  13821. /**
  13822. * Send a draw order
  13823. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13824. * @param indexStart defines the starting index
  13825. * @param indexCount defines the number of index to draw
  13826. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13827. */
  13828. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13829. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13830. };
  13831. /**
  13832. * Draw a list of points
  13833. * @param verticesStart defines the index of first vertex to draw
  13834. * @param verticesCount defines the count of vertices to draw
  13835. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13836. */
  13837. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13838. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13839. };
  13840. /**
  13841. * Draw a list of unindexed primitives
  13842. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13843. * @param verticesStart defines the index of first vertex to draw
  13844. * @param verticesCount defines the count of vertices to draw
  13845. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13846. */
  13847. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13848. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13849. };
  13850. /**
  13851. * Draw a list of indexed primitives
  13852. * @param fillMode defines the primitive to use
  13853. * @param indexStart defines the starting index
  13854. * @param indexCount defines the number of index to draw
  13855. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13856. */
  13857. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13858. // Apply states
  13859. this.applyStates();
  13860. this._drawCalls.addCount(1, false);
  13861. // Render
  13862. var drawMode = this._drawMode(fillMode);
  13863. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13864. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13865. if (instancesCount) {
  13866. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13867. }
  13868. else {
  13869. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13870. }
  13871. };
  13872. /**
  13873. * Draw a list of unindexed primitives
  13874. * @param fillMode defines the primitive to use
  13875. * @param verticesStart defines the index of first vertex to draw
  13876. * @param verticesCount defines the count of vertices to draw
  13877. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13878. */
  13879. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13880. // Apply states
  13881. this.applyStates();
  13882. this._drawCalls.addCount(1, false);
  13883. var drawMode = this._drawMode(fillMode);
  13884. if (instancesCount) {
  13885. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13886. }
  13887. else {
  13888. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13889. }
  13890. };
  13891. Engine.prototype._drawMode = function (fillMode) {
  13892. switch (fillMode) {
  13893. // Triangle views
  13894. case BABYLON.Material.TriangleFillMode:
  13895. return this._gl.TRIANGLES;
  13896. case BABYLON.Material.PointFillMode:
  13897. return this._gl.POINTS;
  13898. case BABYLON.Material.WireFrameFillMode:
  13899. return this._gl.LINES;
  13900. // Draw modes
  13901. case BABYLON.Material.PointListDrawMode:
  13902. return this._gl.POINTS;
  13903. case BABYLON.Material.LineListDrawMode:
  13904. return this._gl.LINES;
  13905. case BABYLON.Material.LineLoopDrawMode:
  13906. return this._gl.LINE_LOOP;
  13907. case BABYLON.Material.LineStripDrawMode:
  13908. return this._gl.LINE_STRIP;
  13909. case BABYLON.Material.TriangleStripDrawMode:
  13910. return this._gl.TRIANGLE_STRIP;
  13911. case BABYLON.Material.TriangleFanDrawMode:
  13912. return this._gl.TRIANGLE_FAN;
  13913. default:
  13914. return this._gl.TRIANGLES;
  13915. }
  13916. };
  13917. // Shaders
  13918. /** @hidden */
  13919. Engine.prototype._releaseEffect = function (effect) {
  13920. if (this._compiledEffects[effect._key]) {
  13921. delete this._compiledEffects[effect._key];
  13922. this._deleteProgram(effect.getProgram());
  13923. }
  13924. };
  13925. /** @hidden */
  13926. Engine.prototype._deleteProgram = function (program) {
  13927. if (program) {
  13928. program.__SPECTOR_rebuildProgram = null;
  13929. if (program.transformFeedback) {
  13930. this.deleteTransformFeedback(program.transformFeedback);
  13931. program.transformFeedback = null;
  13932. }
  13933. this._gl.deleteProgram(program);
  13934. }
  13935. };
  13936. /**
  13937. * Create a new effect (used to store vertex/fragment shaders)
  13938. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13939. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13940. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13941. * @param samplers defines an array of string used to represent textures
  13942. * @param defines defines the string containing the defines to use to compile the shaders
  13943. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13944. * @param onCompiled defines a function to call when the effect creation is successful
  13945. * @param onError defines a function to call when the effect creation has failed
  13946. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13947. * @returns the new Effect
  13948. */
  13949. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13950. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13951. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13952. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13953. if (this._compiledEffects[name]) {
  13954. var compiledEffect = this._compiledEffects[name];
  13955. if (onCompiled && compiledEffect.isReady()) {
  13956. onCompiled(compiledEffect);
  13957. }
  13958. return compiledEffect;
  13959. }
  13960. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13961. effect._key = name;
  13962. this._compiledEffects[name] = effect;
  13963. return effect;
  13964. };
  13965. /**
  13966. * Create an effect to use with particle systems
  13967. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13968. * @param uniformsNames defines a list of attribute names
  13969. * @param samplers defines an array of string used to represent textures
  13970. * @param defines defines the string containing the defines to use to compile the shaders
  13971. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13972. * @param onCompiled defines a function to call when the effect creation is successful
  13973. * @param onError defines a function to call when the effect creation has failed
  13974. * @returns the new Effect
  13975. */
  13976. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13977. if (uniformsNames === void 0) { uniformsNames = []; }
  13978. if (samplers === void 0) { samplers = []; }
  13979. if (defines === void 0) { defines = ""; }
  13980. return this.createEffect({
  13981. vertex: "particles",
  13982. fragmentElement: fragmentName
  13983. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13984. };
  13985. /**
  13986. * Directly creates a webGL program
  13987. * @param vertexCode defines the vertex shader code to use
  13988. * @param fragmentCode defines the fragment shader code to use
  13989. * @param context defines the webGL context to use (if not set, the current one will be used)
  13990. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13991. * @returns the new webGL program
  13992. */
  13993. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13994. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13995. context = context || this._gl;
  13996. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13997. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13998. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13999. };
  14000. /**
  14001. * Creates a webGL program
  14002. * @param vertexCode defines the vertex shader code to use
  14003. * @param fragmentCode defines the fragment shader code to use
  14004. * @param defines defines the string containing the defines to use to compile the shaders
  14005. * @param context defines the webGL context to use (if not set, the current one will be used)
  14006. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14007. * @returns the new webGL program
  14008. */
  14009. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14010. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14011. context = context || this._gl;
  14012. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14013. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14014. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14015. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14016. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14017. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14018. return program;
  14019. };
  14020. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14021. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14022. var shaderProgram = context.createProgram();
  14023. if (!shaderProgram) {
  14024. throw new Error("Unable to create program");
  14025. }
  14026. context.attachShader(shaderProgram, vertexShader);
  14027. context.attachShader(shaderProgram, fragmentShader);
  14028. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14029. var transformFeedback = this.createTransformFeedback();
  14030. this.bindTransformFeedback(transformFeedback);
  14031. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14032. shaderProgram.transformFeedback = transformFeedback;
  14033. }
  14034. context.linkProgram(shaderProgram);
  14035. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14036. this.bindTransformFeedback(null);
  14037. }
  14038. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14039. if (!linked) {
  14040. context.validateProgram(shaderProgram);
  14041. var error = context.getProgramInfoLog(shaderProgram);
  14042. if (error) {
  14043. throw new Error(error);
  14044. }
  14045. }
  14046. context.deleteShader(vertexShader);
  14047. context.deleteShader(fragmentShader);
  14048. return shaderProgram;
  14049. };
  14050. /**
  14051. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14052. * @param shaderProgram defines the webGL program to use
  14053. * @param uniformsNames defines the list of uniform names
  14054. * @returns an array of webGL uniform locations
  14055. */
  14056. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14057. var results = new Array();
  14058. for (var index = 0; index < uniformsNames.length; index++) {
  14059. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14060. }
  14061. return results;
  14062. };
  14063. /**
  14064. * Gets the lsit of active attributes for a given webGL program
  14065. * @param shaderProgram defines the webGL program to use
  14066. * @param attributesNames defines the list of attribute names to get
  14067. * @returns an array of indices indicating the offset of each attribute
  14068. */
  14069. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14070. var results = [];
  14071. for (var index = 0; index < attributesNames.length; index++) {
  14072. try {
  14073. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14074. }
  14075. catch (e) {
  14076. results.push(-1);
  14077. }
  14078. }
  14079. return results;
  14080. };
  14081. /**
  14082. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14083. * @param effect defines the effect to activate
  14084. */
  14085. Engine.prototype.enableEffect = function (effect) {
  14086. if (!effect) {
  14087. return;
  14088. }
  14089. // Use program
  14090. this.bindSamplers(effect);
  14091. this._currentEffect = effect;
  14092. if (effect.onBind) {
  14093. effect.onBind(effect);
  14094. }
  14095. effect.onBindObservable.notifyObservers(effect);
  14096. };
  14097. /**
  14098. * Set the value of an uniform to an array of int32
  14099. * @param uniform defines the webGL uniform location where to store the value
  14100. * @param array defines the array of int32 to store
  14101. */
  14102. Engine.prototype.setIntArray = function (uniform, array) {
  14103. if (!uniform)
  14104. return;
  14105. this._gl.uniform1iv(uniform, array);
  14106. };
  14107. /**
  14108. * Set the value of an uniform to an array of int32 (stored as vec2)
  14109. * @param uniform defines the webGL uniform location where to store the value
  14110. * @param array defines the array of int32 to store
  14111. */
  14112. Engine.prototype.setIntArray2 = function (uniform, array) {
  14113. if (!uniform || array.length % 2 !== 0)
  14114. return;
  14115. this._gl.uniform2iv(uniform, array);
  14116. };
  14117. /**
  14118. * Set the value of an uniform to an array of int32 (stored as vec3)
  14119. * @param uniform defines the webGL uniform location where to store the value
  14120. * @param array defines the array of int32 to store
  14121. */
  14122. Engine.prototype.setIntArray3 = function (uniform, array) {
  14123. if (!uniform || array.length % 3 !== 0)
  14124. return;
  14125. this._gl.uniform3iv(uniform, array);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to an array of int32 (stored as vec4)
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param array defines the array of int32 to store
  14131. */
  14132. Engine.prototype.setIntArray4 = function (uniform, array) {
  14133. if (!uniform || array.length % 4 !== 0)
  14134. return;
  14135. this._gl.uniform4iv(uniform, array);
  14136. };
  14137. /**
  14138. * Set the value of an uniform to an array of float32
  14139. * @param uniform defines the webGL uniform location where to store the value
  14140. * @param array defines the array of float32 to store
  14141. */
  14142. Engine.prototype.setFloatArray = function (uniform, array) {
  14143. if (!uniform)
  14144. return;
  14145. this._gl.uniform1fv(uniform, array);
  14146. };
  14147. /**
  14148. * Set the value of an uniform to an array of float32 (stored as vec2)
  14149. * @param uniform defines the webGL uniform location where to store the value
  14150. * @param array defines the array of float32 to store
  14151. */
  14152. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14153. if (!uniform || array.length % 2 !== 0)
  14154. return;
  14155. this._gl.uniform2fv(uniform, array);
  14156. };
  14157. /**
  14158. * Set the value of an uniform to an array of float32 (stored as vec3)
  14159. * @param uniform defines the webGL uniform location where to store the value
  14160. * @param array defines the array of float32 to store
  14161. */
  14162. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14163. if (!uniform || array.length % 3 !== 0)
  14164. return;
  14165. this._gl.uniform3fv(uniform, array);
  14166. };
  14167. /**
  14168. * Set the value of an uniform to an array of float32 (stored as vec4)
  14169. * @param uniform defines the webGL uniform location where to store the value
  14170. * @param array defines the array of float32 to store
  14171. */
  14172. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14173. if (!uniform || array.length % 4 !== 0)
  14174. return;
  14175. this._gl.uniform4fv(uniform, array);
  14176. };
  14177. /**
  14178. * Set the value of an uniform to an array of number
  14179. * @param uniform defines the webGL uniform location where to store the value
  14180. * @param array defines the array of number to store
  14181. */
  14182. Engine.prototype.setArray = function (uniform, array) {
  14183. if (!uniform)
  14184. return;
  14185. this._gl.uniform1fv(uniform, array);
  14186. };
  14187. /**
  14188. * Set the value of an uniform to an array of number (stored as vec2)
  14189. * @param uniform defines the webGL uniform location where to store the value
  14190. * @param array defines the array of number to store
  14191. */
  14192. Engine.prototype.setArray2 = function (uniform, array) {
  14193. if (!uniform || array.length % 2 !== 0)
  14194. return;
  14195. this._gl.uniform2fv(uniform, array);
  14196. };
  14197. /**
  14198. * Set the value of an uniform to an array of number (stored as vec3)
  14199. * @param uniform defines the webGL uniform location where to store the value
  14200. * @param array defines the array of number to store
  14201. */
  14202. Engine.prototype.setArray3 = function (uniform, array) {
  14203. if (!uniform || array.length % 3 !== 0)
  14204. return;
  14205. this._gl.uniform3fv(uniform, array);
  14206. };
  14207. /**
  14208. * Set the value of an uniform to an array of number (stored as vec4)
  14209. * @param uniform defines the webGL uniform location where to store the value
  14210. * @param array defines the array of number to store
  14211. */
  14212. Engine.prototype.setArray4 = function (uniform, array) {
  14213. if (!uniform || array.length % 4 !== 0)
  14214. return;
  14215. this._gl.uniform4fv(uniform, array);
  14216. };
  14217. /**
  14218. * Set the value of an uniform to an array of float32 (stored as matrices)
  14219. * @param uniform defines the webGL uniform location where to store the value
  14220. * @param matrices defines the array of float32 to store
  14221. */
  14222. Engine.prototype.setMatrices = function (uniform, matrices) {
  14223. if (!uniform)
  14224. return;
  14225. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14226. };
  14227. /**
  14228. * Set the value of an uniform to a matrix
  14229. * @param uniform defines the webGL uniform location where to store the value
  14230. * @param matrix defines the matrix to store
  14231. */
  14232. Engine.prototype.setMatrix = function (uniform, matrix) {
  14233. if (!uniform)
  14234. return;
  14235. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14236. };
  14237. /**
  14238. * Set the value of an uniform to a matrix (3x3)
  14239. * @param uniform defines the webGL uniform location where to store the value
  14240. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14241. */
  14242. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14243. if (!uniform)
  14244. return;
  14245. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to a matrix (2x2)
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14251. */
  14252. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14253. if (!uniform)
  14254. return;
  14255. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14256. };
  14257. /**
  14258. * Set the value of an uniform to a number (int)
  14259. * @param uniform defines the webGL uniform location where to store the value
  14260. * @param value defines the int number to store
  14261. */
  14262. Engine.prototype.setInt = function (uniform, value) {
  14263. if (!uniform)
  14264. return;
  14265. this._gl.uniform1i(uniform, value);
  14266. };
  14267. /**
  14268. * Set the value of an uniform to a number (float)
  14269. * @param uniform defines the webGL uniform location where to store the value
  14270. * @param value defines the float number to store
  14271. */
  14272. Engine.prototype.setFloat = function (uniform, value) {
  14273. if (!uniform)
  14274. return;
  14275. this._gl.uniform1f(uniform, value);
  14276. };
  14277. /**
  14278. * Set the value of an uniform to a vec2
  14279. * @param uniform defines the webGL uniform location where to store the value
  14280. * @param x defines the 1st component of the value
  14281. * @param y defines the 2nd component of the value
  14282. */
  14283. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniform2f(uniform, x, y);
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a vec3
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param x defines the 1st component of the value
  14292. * @param y defines the 2nd component of the value
  14293. * @param z defines the 3rd component of the value
  14294. */
  14295. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14296. if (!uniform)
  14297. return;
  14298. this._gl.uniform3f(uniform, x, y, z);
  14299. };
  14300. /**
  14301. * Set the value of an uniform to a boolean
  14302. * @param uniform defines the webGL uniform location where to store the value
  14303. * @param bool defines the boolean to store
  14304. */
  14305. Engine.prototype.setBool = function (uniform, bool) {
  14306. if (!uniform)
  14307. return;
  14308. this._gl.uniform1i(uniform, bool);
  14309. };
  14310. /**
  14311. * Set the value of an uniform to a vec4
  14312. * @param uniform defines the webGL uniform location where to store the value
  14313. * @param x defines the 1st component of the value
  14314. * @param y defines the 2nd component of the value
  14315. * @param z defines the 3rd component of the value
  14316. * @param w defines the 4th component of the value
  14317. */
  14318. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14319. if (!uniform)
  14320. return;
  14321. this._gl.uniform4f(uniform, x, y, z, w);
  14322. };
  14323. /**
  14324. * Set the value of an uniform to a Color3
  14325. * @param uniform defines the webGL uniform location where to store the value
  14326. * @param color3 defines the color to store
  14327. */
  14328. Engine.prototype.setColor3 = function (uniform, color3) {
  14329. if (!uniform)
  14330. return;
  14331. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14332. };
  14333. /**
  14334. * Set the value of an uniform to a Color3 and an alpha value
  14335. * @param uniform defines the webGL uniform location where to store the value
  14336. * @param color3 defines the color to store
  14337. * @param alpha defines the alpha component to store
  14338. */
  14339. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14340. if (!uniform)
  14341. return;
  14342. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14343. };
  14344. /**
  14345. * Sets a Color4 on a uniform variable
  14346. * @param uniform defines the uniform location
  14347. * @param color4 defines the value to be set
  14348. */
  14349. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14353. };
  14354. // States
  14355. /**
  14356. * Set various states to the webGL context
  14357. * @param culling defines backface culling state
  14358. * @param zOffset defines the value to apply to zOffset (0 by default)
  14359. * @param force defines if states must be applied even if cache is up to date
  14360. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14361. */
  14362. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14363. if (zOffset === void 0) { zOffset = 0; }
  14364. if (reverseSide === void 0) { reverseSide = false; }
  14365. // Culling
  14366. if (this._depthCullingState.cull !== culling || force) {
  14367. this._depthCullingState.cull = culling;
  14368. }
  14369. // Cull face
  14370. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14371. if (this._depthCullingState.cullFace !== cullFace || force) {
  14372. this._depthCullingState.cullFace = cullFace;
  14373. }
  14374. // Z offset
  14375. this.setZOffset(zOffset);
  14376. // Front face
  14377. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14378. if (this._depthCullingState.frontFace !== frontFace || force) {
  14379. this._depthCullingState.frontFace = frontFace;
  14380. }
  14381. };
  14382. /**
  14383. * Set the z offset to apply to current rendering
  14384. * @param value defines the offset to apply
  14385. */
  14386. Engine.prototype.setZOffset = function (value) {
  14387. this._depthCullingState.zOffset = value;
  14388. };
  14389. /**
  14390. * Gets the current value of the zOffset
  14391. * @returns the current zOffset state
  14392. */
  14393. Engine.prototype.getZOffset = function () {
  14394. return this._depthCullingState.zOffset;
  14395. };
  14396. /**
  14397. * Enable or disable depth buffering
  14398. * @param enable defines the state to set
  14399. */
  14400. Engine.prototype.setDepthBuffer = function (enable) {
  14401. this._depthCullingState.depthTest = enable;
  14402. };
  14403. /**
  14404. * Gets a boolean indicating if depth writing is enabled
  14405. * @returns the current depth writing state
  14406. */
  14407. Engine.prototype.getDepthWrite = function () {
  14408. return this._depthCullingState.depthMask;
  14409. };
  14410. /**
  14411. * Enable or disable depth writing
  14412. * @param enable defines the state to set
  14413. */
  14414. Engine.prototype.setDepthWrite = function (enable) {
  14415. this._depthCullingState.depthMask = enable;
  14416. };
  14417. /**
  14418. * Enable or disable color writing
  14419. * @param enable defines the state to set
  14420. */
  14421. Engine.prototype.setColorWrite = function (enable) {
  14422. this._gl.colorMask(enable, enable, enable, enable);
  14423. this._colorWrite = enable;
  14424. };
  14425. /**
  14426. * Gets a boolean indicating if color writing is enabled
  14427. * @returns the current color writing state
  14428. */
  14429. Engine.prototype.getColorWrite = function () {
  14430. return this._colorWrite;
  14431. };
  14432. /**
  14433. * Sets alpha constants used by some alpha blending modes
  14434. * @param r defines the red component
  14435. * @param g defines the green component
  14436. * @param b defines the blue component
  14437. * @param a defines the alpha component
  14438. */
  14439. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14440. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14441. };
  14442. /**
  14443. * Sets the current alpha mode
  14444. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14445. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14446. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14447. */
  14448. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14449. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14450. if (this._alphaMode === mode) {
  14451. return;
  14452. }
  14453. switch (mode) {
  14454. case Engine.ALPHA_DISABLE:
  14455. this._alphaState.alphaBlend = false;
  14456. break;
  14457. case Engine.ALPHA_PREMULTIPLIED:
  14458. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14459. this._alphaState.alphaBlend = true;
  14460. break;
  14461. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14462. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14463. this._alphaState.alphaBlend = true;
  14464. break;
  14465. case Engine.ALPHA_COMBINE:
  14466. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14467. this._alphaState.alphaBlend = true;
  14468. break;
  14469. case Engine.ALPHA_ONEONE:
  14470. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14471. this._alphaState.alphaBlend = true;
  14472. break;
  14473. case Engine.ALPHA_ADD:
  14474. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14475. this._alphaState.alphaBlend = true;
  14476. break;
  14477. case Engine.ALPHA_SUBTRACT:
  14478. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14479. this._alphaState.alphaBlend = true;
  14480. break;
  14481. case Engine.ALPHA_MULTIPLY:
  14482. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14483. this._alphaState.alphaBlend = true;
  14484. break;
  14485. case Engine.ALPHA_MAXIMIZED:
  14486. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14487. this._alphaState.alphaBlend = true;
  14488. break;
  14489. case Engine.ALPHA_INTERPOLATE:
  14490. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14491. this._alphaState.alphaBlend = true;
  14492. break;
  14493. case Engine.ALPHA_SCREENMODE:
  14494. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14495. this._alphaState.alphaBlend = true;
  14496. break;
  14497. }
  14498. if (!noDepthWriteChange) {
  14499. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14500. }
  14501. this._alphaMode = mode;
  14502. };
  14503. /**
  14504. * Gets the current alpha mode
  14505. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14506. * @returns the current alpha mode
  14507. */
  14508. Engine.prototype.getAlphaMode = function () {
  14509. return this._alphaMode;
  14510. };
  14511. // Textures
  14512. /**
  14513. * Clears the list of texture accessible through engine.
  14514. * This can help preventing texture load conflict due to name collision.
  14515. */
  14516. Engine.prototype.clearInternalTexturesCache = function () {
  14517. this._internalTexturesCache = [];
  14518. };
  14519. /**
  14520. * Force the entire cache to be cleared
  14521. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14522. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14523. */
  14524. Engine.prototype.wipeCaches = function (bruteForce) {
  14525. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14526. return;
  14527. }
  14528. this._currentEffect = null;
  14529. this._unpackFlipYCached = null;
  14530. this._viewportCached.x = 0;
  14531. this._viewportCached.y = 0;
  14532. this._viewportCached.z = 0;
  14533. this._viewportCached.w = 0;
  14534. if (bruteForce) {
  14535. this.resetTextureCache();
  14536. this._currentProgram = null;
  14537. this._stencilState.reset();
  14538. this._depthCullingState.reset();
  14539. this.setDepthFunctionToLessOrEqual();
  14540. this._alphaState.reset();
  14541. }
  14542. this._resetVertexBufferBinding();
  14543. this._cachedIndexBuffer = null;
  14544. this._cachedEffectForVertexBuffers = null;
  14545. this._unbindVertexArrayObject();
  14546. this.bindIndexBuffer(null);
  14547. };
  14548. /**
  14549. * Set the compressed texture format to use, based on the formats you have, and the formats
  14550. * supported by the hardware / browser.
  14551. *
  14552. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14553. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14554. * to API arguments needed to compressed textures. This puts the burden on the container
  14555. * generator to house the arcane code for determining these for current & future formats.
  14556. *
  14557. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14558. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14559. *
  14560. * Note: The result of this call is not taken into account when a texture is base64.
  14561. *
  14562. * @param formatsAvailable defines the list of those format families you have created
  14563. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14564. *
  14565. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14566. * @returns The extension selected.
  14567. */
  14568. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14569. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14570. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14571. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14572. return this._textureFormatInUse = this._texturesSupported[i];
  14573. }
  14574. }
  14575. }
  14576. // actively set format to nothing, to allow this to be called more than once
  14577. // and possibly fail the 2nd time
  14578. this._textureFormatInUse = null;
  14579. return null;
  14580. };
  14581. /** @hidden */
  14582. Engine.prototype._createTexture = function () {
  14583. var texture = this._gl.createTexture();
  14584. if (!texture) {
  14585. throw new Error("Unable to create texture");
  14586. }
  14587. return texture;
  14588. };
  14589. /**
  14590. * Usually called from BABYLON.Texture.ts.
  14591. * Passed information to create a WebGLTexture
  14592. * @param urlArg defines a value which contains one of the following:
  14593. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14594. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14595. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14596. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14597. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14598. * @param scene needed for loading to the correct scene
  14599. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14600. * @param onLoad optional callback to be called upon successful completion
  14601. * @param onError optional callback to be called upon failure
  14602. * @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
  14603. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14604. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14605. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14606. */
  14607. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14608. var _this = this;
  14609. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14610. if (onLoad === void 0) { onLoad = null; }
  14611. if (onError === void 0) { onError = null; }
  14612. if (buffer === void 0) { buffer = null; }
  14613. if (fallback === void 0) { fallback = null; }
  14614. if (format === void 0) { format = null; }
  14615. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14616. var fromData = url.substr(0, 5) === "data:";
  14617. var fromBlob = url.substr(0, 5) === "blob:";
  14618. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14619. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14620. // establish the file extension, if possible
  14621. var lastDot = url.lastIndexOf('.');
  14622. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14623. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14624. var isTGA = (extension.indexOf(".tga") === 0);
  14625. // determine if a ktx file should be substituted
  14626. var isKTX = false;
  14627. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14628. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14629. isKTX = true;
  14630. }
  14631. if (scene) {
  14632. scene._addPendingData(texture);
  14633. }
  14634. texture.url = url;
  14635. texture.generateMipMaps = !noMipmap;
  14636. texture.samplingMode = samplingMode;
  14637. texture.invertY = invertY;
  14638. if (!this._doNotHandleContextLost) {
  14639. // Keep a link to the buffer only if we plan to handle context lost
  14640. texture._buffer = buffer;
  14641. }
  14642. var onLoadObserver = null;
  14643. if (onLoad && !fallback) {
  14644. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14645. }
  14646. if (!fallback)
  14647. this._internalTexturesCache.push(texture);
  14648. var onerror = function (message, exception) {
  14649. if (scene) {
  14650. scene._removePendingData(texture);
  14651. }
  14652. if (onLoadObserver && !isKTX) {
  14653. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14654. texture.onLoadedObservable.remove(onLoadObserver);
  14655. }
  14656. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14657. if (isKTX) {
  14658. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14659. }
  14660. else if (BABYLON.Tools.UseFallbackTexture) {
  14661. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14662. }
  14663. if (onError) {
  14664. onError(message || "Unknown error", exception);
  14665. }
  14666. };
  14667. var callback = null;
  14668. // processing for non-image formats
  14669. if (isKTX || isTGA || isDDS) {
  14670. if (isKTX) {
  14671. callback = function (data) {
  14672. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14673. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14674. ktx.uploadLevels(_this._gl, !noMipmap);
  14675. return false;
  14676. }, samplingMode);
  14677. };
  14678. }
  14679. else if (isTGA) {
  14680. callback = function (arrayBuffer) {
  14681. var data = new Uint8Array(arrayBuffer);
  14682. var header = BABYLON.TGATools.GetTGAHeader(data);
  14683. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14684. BABYLON.TGATools.UploadContent(_this._gl, data);
  14685. return false;
  14686. }, samplingMode);
  14687. };
  14688. }
  14689. else if (isDDS) {
  14690. callback = function (data) {
  14691. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14692. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14693. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14694. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14695. return false;
  14696. }, samplingMode);
  14697. };
  14698. }
  14699. if (!buffer) {
  14700. this._loadFile(url, function (data) {
  14701. if (callback) {
  14702. callback(data);
  14703. }
  14704. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14705. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14706. });
  14707. }
  14708. else {
  14709. if (callback) {
  14710. callback(buffer);
  14711. }
  14712. }
  14713. // image format processing
  14714. }
  14715. else {
  14716. var onload = function (img) {
  14717. if (fromBlob && !_this._doNotHandleContextLost) {
  14718. // We need to store the image if we need to rebuild the texture
  14719. // in case of a webgl context lost
  14720. texture._buffer = img;
  14721. }
  14722. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14723. var gl = _this._gl;
  14724. var isPot = (img.width === potWidth && img.height === potHeight);
  14725. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14726. if (isPot) {
  14727. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14728. return false;
  14729. }
  14730. // Using shaders to rescale because canvas.drawImage is lossy
  14731. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14732. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14733. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14734. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14735. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14736. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14737. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14738. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14739. _this._releaseTexture(source);
  14740. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14741. continuationCallback();
  14742. });
  14743. return true;
  14744. }, samplingMode);
  14745. };
  14746. if (!fromData || isBase64) {
  14747. if (buffer instanceof HTMLImageElement) {
  14748. onload(buffer);
  14749. }
  14750. else {
  14751. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14752. }
  14753. }
  14754. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14755. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14756. }
  14757. else {
  14758. onload(buffer);
  14759. }
  14760. }
  14761. return texture;
  14762. };
  14763. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14764. var _this = this;
  14765. var rtt = this.createRenderTargetTexture({
  14766. width: destination.width,
  14767. height: destination.height,
  14768. }, {
  14769. generateMipMaps: false,
  14770. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14771. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14772. generateDepthBuffer: false,
  14773. generateStencilBuffer: false
  14774. });
  14775. if (!this._rescalePostProcess) {
  14776. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14777. }
  14778. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14779. _this._rescalePostProcess.onApply = function (effect) {
  14780. effect._bindTexture("textureSampler", source);
  14781. };
  14782. var hostingScene = scene;
  14783. if (!hostingScene) {
  14784. hostingScene = _this.scenes[_this.scenes.length - 1];
  14785. }
  14786. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14787. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14788. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14789. _this.unBindFramebuffer(rtt);
  14790. _this._releaseTexture(rtt);
  14791. if (onComplete) {
  14792. onComplete();
  14793. }
  14794. });
  14795. };
  14796. /**
  14797. * Update a raw texture
  14798. * @param texture defines the texture to update
  14799. * @param data defines the data to store in the texture
  14800. * @param format defines the format of the data
  14801. * @param invertY defines if data must be stored with Y axis inverted
  14802. * @param compression defines the compression used (null by default)
  14803. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14804. */
  14805. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14806. if (compression === void 0) { compression = null; }
  14807. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14808. if (!texture) {
  14809. return;
  14810. }
  14811. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14812. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14813. // babylon's internalFormat but gl's texImage2D format
  14814. var internalFormat = this._getInternalFormat(format);
  14815. var textureType = this._getWebGLTextureType(type);
  14816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14817. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14818. if (!this._doNotHandleContextLost) {
  14819. texture._bufferView = data;
  14820. texture.format = format;
  14821. texture.type = type;
  14822. texture.invertY = invertY;
  14823. texture._compression = compression;
  14824. }
  14825. if (texture.width % 4 !== 0) {
  14826. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14827. }
  14828. if (compression && data) {
  14829. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14830. }
  14831. else {
  14832. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14833. }
  14834. if (texture.generateMipMaps) {
  14835. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14836. }
  14837. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14838. // this.resetTextureCache();
  14839. texture.isReady = true;
  14840. };
  14841. /**
  14842. * Creates a raw texture
  14843. * @param data defines the data to store in the texture
  14844. * @param width defines the width of the texture
  14845. * @param height defines the height of the texture
  14846. * @param format defines the format of the data
  14847. * @param generateMipMaps defines if the engine should generate the mip levels
  14848. * @param invertY defines if data must be stored with Y axis inverted
  14849. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14850. * @param compression defines the compression used (null by default)
  14851. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14852. * @returns the raw texture inside an InternalTexture
  14853. */
  14854. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14855. if (compression === void 0) { compression = null; }
  14856. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14857. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14858. texture.baseWidth = width;
  14859. texture.baseHeight = height;
  14860. texture.width = width;
  14861. texture.height = height;
  14862. texture.format = format;
  14863. texture.generateMipMaps = generateMipMaps;
  14864. texture.samplingMode = samplingMode;
  14865. texture.invertY = invertY;
  14866. texture._compression = compression;
  14867. texture.type = type;
  14868. if (!this._doNotHandleContextLost) {
  14869. texture._bufferView = data;
  14870. }
  14871. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14872. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14873. // Filters
  14874. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14875. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14876. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14877. if (generateMipMaps) {
  14878. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14879. }
  14880. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14881. this._internalTexturesCache.push(texture);
  14882. return texture;
  14883. };
  14884. /** @hidden */
  14885. Engine.prototype._unpackFlipY = function (value) {
  14886. if (this._unpackFlipYCached !== value) {
  14887. this._unpackFlipYCached = value;
  14888. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14889. }
  14890. };
  14891. /**
  14892. * Creates a dynamic texture
  14893. * @param width defines the width of the texture
  14894. * @param height defines the height of the texture
  14895. * @param generateMipMaps defines if the engine should generate the mip levels
  14896. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14897. * @returns the dynamic texture inside an InternalTexture
  14898. */
  14899. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14900. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14901. texture.baseWidth = width;
  14902. texture.baseHeight = height;
  14903. if (generateMipMaps) {
  14904. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14905. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14906. }
  14907. // this.resetTextureCache();
  14908. texture.width = width;
  14909. texture.height = height;
  14910. texture.isReady = false;
  14911. texture.generateMipMaps = generateMipMaps;
  14912. texture.samplingMode = samplingMode;
  14913. this.updateTextureSamplingMode(samplingMode, texture);
  14914. this._internalTexturesCache.push(texture);
  14915. return texture;
  14916. };
  14917. /**
  14918. * Update the sampling mode of a given texture
  14919. * @param samplingMode defines the required sampling mode
  14920. * @param texture defines the texture to update
  14921. */
  14922. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14923. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14924. if (texture.isCube) {
  14925. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14926. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14927. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14928. }
  14929. else if (texture.is3D) {
  14930. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14931. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14932. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14933. }
  14934. else {
  14935. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14936. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14937. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14938. }
  14939. texture.samplingMode = samplingMode;
  14940. };
  14941. /**
  14942. * Update the content of a dynamic texture
  14943. * @param texture defines the texture to update
  14944. * @param canvas defines the canvas containing the source
  14945. * @param invertY defines if data must be stored with Y axis inverted
  14946. * @param premulAlpha defines if alpha is stored as premultiplied
  14947. * @param format defines the format of the data
  14948. */
  14949. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14950. if (premulAlpha === void 0) { premulAlpha = false; }
  14951. if (!texture) {
  14952. return;
  14953. }
  14954. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14955. this._unpackFlipY(invertY);
  14956. if (premulAlpha) {
  14957. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14958. }
  14959. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14960. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14961. if (texture.generateMipMaps) {
  14962. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14963. }
  14964. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14965. if (premulAlpha) {
  14966. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14967. }
  14968. texture.isReady = true;
  14969. };
  14970. /**
  14971. * Update a video texture
  14972. * @param texture defines the texture to update
  14973. * @param video defines the video element to use
  14974. * @param invertY defines if data must be stored with Y axis inverted
  14975. */
  14976. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14977. if (!texture || texture._isDisabled) {
  14978. return;
  14979. }
  14980. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14981. this._unpackFlipY(!invertY); // Video are upside down by default
  14982. try {
  14983. // Testing video texture support
  14984. if (this._videoTextureSupported === undefined) {
  14985. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14986. if (this._gl.getError() !== 0) {
  14987. this._videoTextureSupported = false;
  14988. }
  14989. else {
  14990. this._videoTextureSupported = true;
  14991. }
  14992. }
  14993. // Copy video through the current working canvas if video texture is not supported
  14994. if (!this._videoTextureSupported) {
  14995. if (!texture._workingCanvas) {
  14996. texture._workingCanvas = document.createElement("canvas");
  14997. var context = texture._workingCanvas.getContext("2d");
  14998. if (!context) {
  14999. throw new Error("Unable to get 2d context");
  15000. }
  15001. texture._workingContext = context;
  15002. texture._workingCanvas.width = texture.width;
  15003. texture._workingCanvas.height = texture.height;
  15004. }
  15005. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15006. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15007. }
  15008. else {
  15009. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15010. }
  15011. if (texture.generateMipMaps) {
  15012. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15013. }
  15014. if (!wasPreviouslyBound) {
  15015. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15016. }
  15017. // this.resetTextureCache();
  15018. texture.isReady = true;
  15019. }
  15020. catch (ex) {
  15021. // Something unexpected
  15022. // Let's disable the texture
  15023. texture._isDisabled = true;
  15024. }
  15025. };
  15026. /**
  15027. * Updates a depth texture Comparison Mode and Function.
  15028. * If the comparison Function is equal to 0, the mode will be set to none.
  15029. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15030. * @param texture The texture to set the comparison function for
  15031. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15032. */
  15033. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15034. if (this.webGLVersion === 1) {
  15035. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15036. return;
  15037. }
  15038. var gl = this._gl;
  15039. if (texture.isCube) {
  15040. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15041. if (comparisonFunction === 0) {
  15042. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15043. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15044. }
  15045. else {
  15046. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15047. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15048. }
  15049. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15050. }
  15051. else {
  15052. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15053. if (comparisonFunction === 0) {
  15054. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15055. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15056. }
  15057. else {
  15058. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15059. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15060. }
  15061. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15062. }
  15063. texture._comparisonFunction = comparisonFunction;
  15064. };
  15065. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15066. var width = size.width || size;
  15067. var height = size.height || size;
  15068. internalTexture.baseWidth = width;
  15069. internalTexture.baseHeight = height;
  15070. internalTexture.width = width;
  15071. internalTexture.height = height;
  15072. internalTexture.isReady = true;
  15073. internalTexture.samples = 1;
  15074. internalTexture.generateMipMaps = false;
  15075. internalTexture._generateDepthBuffer = true;
  15076. internalTexture._generateStencilBuffer = generateStencil;
  15077. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15078. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15079. internalTexture._comparisonFunction = comparisonFunction;
  15080. var gl = this._gl;
  15081. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15082. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15083. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15084. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15085. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15086. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15087. if (comparisonFunction === 0) {
  15088. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15089. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15090. }
  15091. else {
  15092. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15093. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15094. }
  15095. };
  15096. /**
  15097. * Creates a depth stencil texture.
  15098. * This is only available in WebGL 2 or with the depth texture extension available.
  15099. * @param size The size of face edge in the texture.
  15100. * @param options The options defining the texture.
  15101. * @returns The texture
  15102. */
  15103. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15104. if (options.isCube) {
  15105. var width = size.width || size;
  15106. return this._createDepthStencilCubeTexture(width, options);
  15107. }
  15108. else {
  15109. return this._createDepthStencilTexture(size, options);
  15110. }
  15111. };
  15112. /**
  15113. * Creates a depth stencil texture.
  15114. * This is only available in WebGL 2 or with the depth texture extension available.
  15115. * @param size The size of face edge in the texture.
  15116. * @param options The options defining the texture.
  15117. * @returns The texture
  15118. */
  15119. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15120. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15121. if (!this._caps.depthTextureExtension) {
  15122. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15123. return internalTexture;
  15124. }
  15125. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15126. var gl = this._gl;
  15127. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15128. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15129. if (this.webGLVersion > 1) {
  15130. if (internalOptions.generateStencil) {
  15131. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15132. }
  15133. else {
  15134. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15135. }
  15136. }
  15137. else {
  15138. if (internalOptions.generateStencil) {
  15139. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15140. }
  15141. else {
  15142. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15143. }
  15144. }
  15145. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15146. return internalTexture;
  15147. };
  15148. /**
  15149. * Creates a depth stencil cube texture.
  15150. * This is only available in WebGL 2.
  15151. * @param size The size of face edge in the cube texture.
  15152. * @param options The options defining the cube texture.
  15153. * @returns The cube texture
  15154. */
  15155. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15156. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15157. internalTexture.isCube = true;
  15158. if (this.webGLVersion === 1) {
  15159. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15160. return internalTexture;
  15161. }
  15162. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15163. var gl = this._gl;
  15164. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15165. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15166. // Create the depth/stencil buffer
  15167. for (var face = 0; face < 6; face++) {
  15168. if (internalOptions.generateStencil) {
  15169. 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);
  15170. }
  15171. else {
  15172. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15173. }
  15174. }
  15175. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15176. return internalTexture;
  15177. };
  15178. /**
  15179. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15180. * @param renderTarget The render target to set the frame buffer for
  15181. */
  15182. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15183. // Create the framebuffer
  15184. var internalTexture = renderTarget.getInternalTexture();
  15185. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15186. return;
  15187. }
  15188. var gl = this._gl;
  15189. var depthStencilTexture = renderTarget.depthStencilTexture;
  15190. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15191. if (depthStencilTexture.isCube) {
  15192. if (depthStencilTexture._generateStencilBuffer) {
  15193. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15194. }
  15195. else {
  15196. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15197. }
  15198. }
  15199. else {
  15200. if (depthStencilTexture._generateStencilBuffer) {
  15201. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15202. }
  15203. else {
  15204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15205. }
  15206. }
  15207. this.bindUnboundFramebuffer(null);
  15208. };
  15209. /**
  15210. * Creates a new render target texture
  15211. * @param size defines the size of the texture
  15212. * @param options defines the options used to create the texture
  15213. * @returns a new render target texture stored in an InternalTexture
  15214. */
  15215. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15216. var fullOptions = new RenderTargetCreationOptions();
  15217. if (options !== undefined && typeof options === "object") {
  15218. fullOptions.generateMipMaps = options.generateMipMaps;
  15219. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15220. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15221. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15222. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15223. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15224. }
  15225. else {
  15226. fullOptions.generateMipMaps = options;
  15227. fullOptions.generateDepthBuffer = true;
  15228. fullOptions.generateStencilBuffer = false;
  15229. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15230. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15231. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15232. }
  15233. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15234. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15235. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15236. }
  15237. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15238. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15239. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15240. }
  15241. var gl = this._gl;
  15242. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15243. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15244. var width = size.width || size;
  15245. var height = size.height || size;
  15246. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15247. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15248. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15249. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15250. }
  15251. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15255. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15256. // Create the framebuffer
  15257. var currentFrameBuffer = this._currentFramebuffer;
  15258. var framebuffer = gl.createFramebuffer();
  15259. this.bindUnboundFramebuffer(framebuffer);
  15260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15261. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15262. if (fullOptions.generateMipMaps) {
  15263. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15264. }
  15265. // Unbind
  15266. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15267. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15268. this.bindUnboundFramebuffer(currentFrameBuffer);
  15269. texture._framebuffer = framebuffer;
  15270. texture.baseWidth = width;
  15271. texture.baseHeight = height;
  15272. texture.width = width;
  15273. texture.height = height;
  15274. texture.isReady = true;
  15275. texture.samples = 1;
  15276. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15277. texture.samplingMode = fullOptions.samplingMode;
  15278. texture.type = fullOptions.type;
  15279. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15280. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15281. // this.resetTextureCache();
  15282. this._internalTexturesCache.push(texture);
  15283. return texture;
  15284. };
  15285. /**
  15286. * Create a multi render target texture
  15287. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15288. * @param size defines the size of the texture
  15289. * @param options defines the creation options
  15290. * @returns the cube texture as an InternalTexture
  15291. */
  15292. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15293. var generateMipMaps = false;
  15294. var generateDepthBuffer = true;
  15295. var generateStencilBuffer = false;
  15296. var generateDepthTexture = false;
  15297. var textureCount = 1;
  15298. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15299. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15300. var types = new Array();
  15301. var samplingModes = new Array();
  15302. if (options !== undefined) {
  15303. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15304. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15305. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15306. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15307. textureCount = options.textureCount || 1;
  15308. if (options.types) {
  15309. types = options.types;
  15310. }
  15311. if (options.samplingModes) {
  15312. samplingModes = options.samplingModes;
  15313. }
  15314. }
  15315. var gl = this._gl;
  15316. // Create the framebuffer
  15317. var framebuffer = gl.createFramebuffer();
  15318. this.bindUnboundFramebuffer(framebuffer);
  15319. var width = size.width || size;
  15320. var height = size.height || size;
  15321. var textures = [];
  15322. var attachments = [];
  15323. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15324. for (var i = 0; i < textureCount; i++) {
  15325. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15326. var type = types[i] || defaultType;
  15327. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15328. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15329. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15330. }
  15331. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15332. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15333. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15334. }
  15335. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15336. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15337. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15338. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15339. }
  15340. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15341. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15342. textures.push(texture);
  15343. attachments.push(attachment);
  15344. gl.activeTexture(gl["TEXTURE" + i]);
  15345. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15346. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15347. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15348. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15349. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15350. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15351. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15352. if (generateMipMaps) {
  15353. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15354. }
  15355. // Unbind
  15356. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15357. texture._framebuffer = framebuffer;
  15358. texture._depthStencilBuffer = depthStencilBuffer;
  15359. texture.baseWidth = width;
  15360. texture.baseHeight = height;
  15361. texture.width = width;
  15362. texture.height = height;
  15363. texture.isReady = true;
  15364. texture.samples = 1;
  15365. texture.generateMipMaps = generateMipMaps;
  15366. texture.samplingMode = samplingMode;
  15367. texture.type = type;
  15368. texture._generateDepthBuffer = generateDepthBuffer;
  15369. texture._generateStencilBuffer = generateStencilBuffer;
  15370. texture._attachments = attachments;
  15371. this._internalTexturesCache.push(texture);
  15372. }
  15373. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15374. // Depth texture
  15375. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15376. gl.activeTexture(gl.TEXTURE0);
  15377. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15378. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15379. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15380. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15381. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15382. 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);
  15383. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15384. depthTexture._framebuffer = framebuffer;
  15385. depthTexture.baseWidth = width;
  15386. depthTexture.baseHeight = height;
  15387. depthTexture.width = width;
  15388. depthTexture.height = height;
  15389. depthTexture.isReady = true;
  15390. depthTexture.samples = 1;
  15391. depthTexture.generateMipMaps = generateMipMaps;
  15392. depthTexture.samplingMode = gl.NEAREST;
  15393. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15394. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15395. textures.push(depthTexture);
  15396. this._internalTexturesCache.push(depthTexture);
  15397. }
  15398. gl.drawBuffers(attachments);
  15399. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15400. this.bindUnboundFramebuffer(null);
  15401. this.resetTextureCache();
  15402. return textures;
  15403. };
  15404. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15405. if (samples === void 0) { samples = 1; }
  15406. var depthStencilBuffer = null;
  15407. var gl = this._gl;
  15408. // Create the depth/stencil buffer
  15409. if (generateStencilBuffer) {
  15410. depthStencilBuffer = gl.createRenderbuffer();
  15411. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15412. if (samples > 1) {
  15413. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15414. }
  15415. else {
  15416. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15417. }
  15418. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15419. }
  15420. else if (generateDepthBuffer) {
  15421. depthStencilBuffer = gl.createRenderbuffer();
  15422. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15423. if (samples > 1) {
  15424. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15425. }
  15426. else {
  15427. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15428. }
  15429. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15430. }
  15431. return depthStencilBuffer;
  15432. };
  15433. /**
  15434. * Updates the sample count of a render target texture
  15435. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15436. * @param texture defines the texture to update
  15437. * @param samples defines the sample count to set
  15438. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15439. */
  15440. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15441. if (this.webGLVersion < 2 || !texture) {
  15442. return 1;
  15443. }
  15444. if (texture.samples === samples) {
  15445. return samples;
  15446. }
  15447. var gl = this._gl;
  15448. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15449. // Dispose previous render buffers
  15450. if (texture._depthStencilBuffer) {
  15451. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15452. texture._depthStencilBuffer = null;
  15453. }
  15454. if (texture._MSAAFramebuffer) {
  15455. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15456. texture._MSAAFramebuffer = null;
  15457. }
  15458. if (texture._MSAARenderBuffer) {
  15459. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15460. texture._MSAARenderBuffer = null;
  15461. }
  15462. if (samples > 1) {
  15463. var framebuffer = gl.createFramebuffer();
  15464. if (!framebuffer) {
  15465. throw new Error("Unable to create multi sampled framebuffer");
  15466. }
  15467. texture._MSAAFramebuffer = framebuffer;
  15468. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15469. var colorRenderbuffer = gl.createRenderbuffer();
  15470. if (!colorRenderbuffer) {
  15471. throw new Error("Unable to create multi sampled framebuffer");
  15472. }
  15473. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15474. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15475. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15476. texture._MSAARenderBuffer = colorRenderbuffer;
  15477. }
  15478. else {
  15479. this.bindUnboundFramebuffer(texture._framebuffer);
  15480. }
  15481. texture.samples = samples;
  15482. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15483. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15484. this.bindUnboundFramebuffer(null);
  15485. return samples;
  15486. };
  15487. /**
  15488. * Update the sample count for a given multiple render target texture
  15489. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15490. * @param textures defines the textures to update
  15491. * @param samples defines the sample count to set
  15492. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15493. */
  15494. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15495. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15496. return 1;
  15497. }
  15498. if (textures[0].samples === samples) {
  15499. return samples;
  15500. }
  15501. var gl = this._gl;
  15502. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15503. // Dispose previous render buffers
  15504. if (textures[0]._depthStencilBuffer) {
  15505. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15506. textures[0]._depthStencilBuffer = null;
  15507. }
  15508. if (textures[0]._MSAAFramebuffer) {
  15509. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15510. textures[0]._MSAAFramebuffer = null;
  15511. }
  15512. for (var i = 0; i < textures.length; i++) {
  15513. if (textures[i]._MSAARenderBuffer) {
  15514. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15515. textures[i]._MSAARenderBuffer = null;
  15516. }
  15517. }
  15518. if (samples > 1) {
  15519. var framebuffer = gl.createFramebuffer();
  15520. if (!framebuffer) {
  15521. throw new Error("Unable to create multi sampled framebuffer");
  15522. }
  15523. this.bindUnboundFramebuffer(framebuffer);
  15524. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15525. var attachments = [];
  15526. for (var i = 0; i < textures.length; i++) {
  15527. var texture = textures[i];
  15528. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15529. var colorRenderbuffer = gl.createRenderbuffer();
  15530. if (!colorRenderbuffer) {
  15531. throw new Error("Unable to create multi sampled framebuffer");
  15532. }
  15533. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15534. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15535. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15536. texture._MSAAFramebuffer = framebuffer;
  15537. texture._MSAARenderBuffer = colorRenderbuffer;
  15538. texture.samples = samples;
  15539. texture._depthStencilBuffer = depthStencilBuffer;
  15540. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15541. attachments.push(attachment);
  15542. }
  15543. gl.drawBuffers(attachments);
  15544. }
  15545. else {
  15546. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15547. }
  15548. this.bindUnboundFramebuffer(null);
  15549. return samples;
  15550. };
  15551. /** @hidden */
  15552. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15553. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15554. };
  15555. /** @hidden */
  15556. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15557. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15558. };
  15559. /** @hidden */
  15560. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15561. var gl = this._gl;
  15562. var textureType = this._getWebGLTextureType(texture.type);
  15563. var format = this._getInternalFormat(texture.format);
  15564. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15565. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15566. this._bindTextureDirectly(bindTarget, texture, true);
  15567. this._unpackFlipY(texture.invertY);
  15568. var target = gl.TEXTURE_2D;
  15569. if (texture.isCube) {
  15570. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15571. }
  15572. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15573. this._bindTextureDirectly(bindTarget, null, true);
  15574. };
  15575. /**
  15576. * Creates a new render target cube texture
  15577. * @param size defines the size of the texture
  15578. * @param options defines the options used to create the texture
  15579. * @returns a new render target cube texture stored in an InternalTexture
  15580. */
  15581. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15582. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15583. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15584. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15585. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15586. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15587. }
  15588. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15589. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15590. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15591. }
  15592. var gl = this._gl;
  15593. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15594. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15595. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15596. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15597. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15598. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15599. }
  15600. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15601. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15604. for (var face = 0; face < 6; face++) {
  15605. 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);
  15606. }
  15607. // Create the framebuffer
  15608. var framebuffer = gl.createFramebuffer();
  15609. this.bindUnboundFramebuffer(framebuffer);
  15610. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15611. // MipMaps
  15612. if (fullOptions.generateMipMaps) {
  15613. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15614. }
  15615. // Unbind
  15616. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15617. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15618. this.bindUnboundFramebuffer(null);
  15619. texture._framebuffer = framebuffer;
  15620. texture.width = size;
  15621. texture.height = size;
  15622. texture.isReady = true;
  15623. texture.isCube = true;
  15624. texture.samples = 1;
  15625. texture.generateMipMaps = fullOptions.generateMipMaps;
  15626. texture.samplingMode = fullOptions.samplingMode;
  15627. texture.type = fullOptions.type;
  15628. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15629. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15630. this._internalTexturesCache.push(texture);
  15631. return texture;
  15632. };
  15633. /**
  15634. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15635. * @param rootUrl defines the url where the file to load is located
  15636. * @param scene defines the current scene
  15637. * @param lodScale defines scale to apply to the mip map selection
  15638. * @param lodOffset defines offset to apply to the mip map selection
  15639. * @param onLoad defines an optional callback raised when the texture is loaded
  15640. * @param onError defines an optional callback raised if there is an issue to load the texture
  15641. * @param format defines the format of the data
  15642. * @param forcedExtension defines the extension to use to pick the right loader
  15643. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15644. * @returns the cube texture as an InternalTexture
  15645. */
  15646. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15647. var _this = this;
  15648. if (onLoad === void 0) { onLoad = null; }
  15649. if (onError === void 0) { onError = null; }
  15650. if (forcedExtension === void 0) { forcedExtension = null; }
  15651. if (createPolynomials === void 0) { createPolynomials = true; }
  15652. var callback = function (loadData) {
  15653. if (!loadData) {
  15654. if (onLoad) {
  15655. onLoad(null);
  15656. }
  15657. return;
  15658. }
  15659. var texture = loadData.texture;
  15660. if (!createPolynomials) {
  15661. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15662. }
  15663. else if (loadData.info.sphericalPolynomial) {
  15664. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15665. }
  15666. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15667. if (_this._caps.textureLOD) {
  15668. // Do not add extra process if texture lod is supported.
  15669. if (onLoad) {
  15670. onLoad(texture);
  15671. }
  15672. return;
  15673. }
  15674. var mipSlices = 3;
  15675. var gl = _this._gl;
  15676. var width = loadData.width;
  15677. if (!width) {
  15678. return;
  15679. }
  15680. var textures = [];
  15681. for (var i = 0; i < mipSlices; i++) {
  15682. //compute LOD from even spacing in smoothness (matching shader calculation)
  15683. var smoothness = i / (mipSlices - 1);
  15684. var roughness = 1 - smoothness;
  15685. var minLODIndex = lodOffset; // roughness = 0
  15686. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15687. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15688. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15689. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15690. glTextureFromLod.isCube = true;
  15691. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15695. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15696. if (loadData.isDDS) {
  15697. var info = loadData.info;
  15698. var data = loadData.data;
  15699. _this._unpackFlipY(info.isCompressed);
  15700. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15701. }
  15702. else {
  15703. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15704. }
  15705. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15706. // Wrap in a base texture for easy binding.
  15707. var lodTexture = new BABYLON.BaseTexture(scene);
  15708. lodTexture.isCube = true;
  15709. lodTexture._texture = glTextureFromLod;
  15710. glTextureFromLod.isReady = true;
  15711. textures.push(lodTexture);
  15712. }
  15713. texture._lodTextureHigh = textures[2];
  15714. texture._lodTextureMid = textures[1];
  15715. texture._lodTextureLow = textures[0];
  15716. if (onLoad) {
  15717. onLoad(texture);
  15718. }
  15719. };
  15720. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15721. };
  15722. /**
  15723. * Creates a cube texture
  15724. * @param rootUrl defines the url where the files to load is located
  15725. * @param scene defines the current scene
  15726. * @param files defines the list of files to load (1 per face)
  15727. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15728. * @param onLoad defines an optional callback raised when the texture is loaded
  15729. * @param onError defines an optional callback raised if there is an issue to load the texture
  15730. * @param format defines the format of the data
  15731. * @param forcedExtension defines the extension to use to pick the right loader
  15732. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15733. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15734. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15735. * @returns the cube texture as an InternalTexture
  15736. */
  15737. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset) {
  15738. var _this = this;
  15739. if (onLoad === void 0) { onLoad = null; }
  15740. if (onError === void 0) { onError = null; }
  15741. if (forcedExtension === void 0) { forcedExtension = null; }
  15742. if (createPolynomials === void 0) { createPolynomials = false; }
  15743. if (lodScale === void 0) { lodScale = 0; }
  15744. if (lodOffset === void 0) { lodOffset = 0; }
  15745. var gl = this._gl;
  15746. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15747. texture.isCube = true;
  15748. texture.url = rootUrl;
  15749. texture.generateMipMaps = !noMipmap;
  15750. texture._lodGenerationScale = lodScale;
  15751. texture._lodGenerationOffset = lodOffset;
  15752. if (!this._doNotHandleContextLost) {
  15753. texture._extension = forcedExtension;
  15754. texture._files = files;
  15755. }
  15756. var isKTX = false;
  15757. var isDDS = false;
  15758. var isEnv = false;
  15759. var lastDot = rootUrl.lastIndexOf('.');
  15760. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15761. if (this._textureFormatInUse) {
  15762. extension = this._textureFormatInUse;
  15763. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15764. isKTX = true;
  15765. }
  15766. else {
  15767. isDDS = (extension === ".dds");
  15768. isEnv = (extension === ".env");
  15769. }
  15770. var onerror = function (request, exception) {
  15771. if (onError && request) {
  15772. onError(request.status + " " + request.statusText, exception);
  15773. }
  15774. };
  15775. if (isKTX) {
  15776. this._loadFile(rootUrl, function (data) {
  15777. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15778. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15779. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15780. _this._unpackFlipY(true);
  15781. ktx.uploadLevels(_this._gl, !noMipmap);
  15782. _this.setCubeMapTextureParams(gl, loadMipmap);
  15783. texture.width = ktx.pixelWidth;
  15784. texture.height = ktx.pixelHeight;
  15785. texture.isReady = true;
  15786. }, undefined, undefined, true, onerror);
  15787. }
  15788. else if (isEnv) {
  15789. this._loadFile(rootUrl, function (data) {
  15790. data = data;
  15791. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15792. if (info) {
  15793. texture.width = info.width;
  15794. texture.height = info.width;
  15795. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15796. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15797. texture.isReady = true;
  15798. if (onLoad) {
  15799. onLoad();
  15800. }
  15801. });
  15802. }
  15803. else if (onError) {
  15804. onError("Can not parse the environment file", null);
  15805. }
  15806. }, undefined, undefined, true, onerror);
  15807. }
  15808. else if (isDDS) {
  15809. if (files && files.length === 6) {
  15810. this._cascadeLoadFiles(scene, function (imgs) {
  15811. var info;
  15812. var loadMipmap = false;
  15813. var width = 0;
  15814. for (var index = 0; index < imgs.length; index++) {
  15815. var data = imgs[index];
  15816. info = BABYLON.DDSTools.GetDDSInfo(data);
  15817. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15818. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15819. _this._unpackFlipY(info.isCompressed);
  15820. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15821. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15822. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15823. }
  15824. texture.width = info.width;
  15825. texture.height = info.height;
  15826. texture.type = info.textureType;
  15827. width = info.width;
  15828. }
  15829. _this.setCubeMapTextureParams(gl, loadMipmap);
  15830. texture.isReady = true;
  15831. if (onLoad) {
  15832. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15833. }
  15834. }, files, onError);
  15835. }
  15836. else {
  15837. this._loadFile(rootUrl, function (data) {
  15838. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15839. if (createPolynomials) {
  15840. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15841. }
  15842. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15843. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15844. _this._unpackFlipY(info.isCompressed);
  15845. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15846. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15847. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15848. }
  15849. _this.setCubeMapTextureParams(gl, loadMipmap);
  15850. texture.width = info.width;
  15851. texture.height = info.height;
  15852. texture.isReady = true;
  15853. texture.type = info.textureType;
  15854. if (onLoad) {
  15855. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15856. }
  15857. }, undefined, undefined, true, onerror);
  15858. }
  15859. }
  15860. else {
  15861. if (!files) {
  15862. throw new Error("Cannot load cubemap because files were not defined");
  15863. }
  15864. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15865. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15866. var height = width;
  15867. _this._prepareWorkingCanvas();
  15868. if (!_this._workingCanvas || !_this._workingContext) {
  15869. return;
  15870. }
  15871. _this._workingCanvas.width = width;
  15872. _this._workingCanvas.height = height;
  15873. var faces = [
  15874. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15875. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15876. ];
  15877. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15878. _this._unpackFlipY(false);
  15879. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15880. for (var index = 0; index < faces.length; index++) {
  15881. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15882. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15883. }
  15884. if (!noMipmap) {
  15885. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15886. }
  15887. _this.setCubeMapTextureParams(gl, !noMipmap);
  15888. texture.width = width;
  15889. texture.height = height;
  15890. texture.isReady = true;
  15891. if (format) {
  15892. texture.format = format;
  15893. }
  15894. texture.onLoadedObservable.notifyObservers(texture);
  15895. texture.onLoadedObservable.clear();
  15896. if (onLoad) {
  15897. onLoad();
  15898. }
  15899. }, files, onError);
  15900. }
  15901. this._internalTexturesCache.push(texture);
  15902. return texture;
  15903. };
  15904. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15905. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15906. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15909. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15910. // this.resetTextureCache();
  15911. };
  15912. /**
  15913. * Update a raw cube texture
  15914. * @param texture defines the texture to udpdate
  15915. * @param data defines the data to store
  15916. * @param format defines the data format
  15917. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15918. * @param invertY defines if data must be stored with Y axis inverted
  15919. * @param compression defines the compression used (null by default)
  15920. * @param level defines which level of the texture to update
  15921. */
  15922. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15923. if (compression === void 0) { compression = null; }
  15924. if (level === void 0) { level = 0; }
  15925. texture._bufferViewArray = data;
  15926. texture.format = format;
  15927. texture.type = type;
  15928. texture.invertY = invertY;
  15929. texture._compression = compression;
  15930. var gl = this._gl;
  15931. var textureType = this._getWebGLTextureType(type);
  15932. var internalFormat = this._getInternalFormat(format);
  15933. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15934. var needConversion = false;
  15935. if (internalFormat === gl.RGB) {
  15936. internalFormat = gl.RGBA;
  15937. needConversion = true;
  15938. }
  15939. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15940. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15941. if (texture.width % 4 !== 0) {
  15942. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15943. }
  15944. // Data are known to be in +X +Y +Z -X -Y -Z
  15945. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15946. var faceData = data[faceIndex];
  15947. if (compression) {
  15948. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15949. }
  15950. else {
  15951. if (needConversion) {
  15952. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15953. }
  15954. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15955. }
  15956. }
  15957. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15958. if (isPot && texture.generateMipMaps && level === 0) {
  15959. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15960. }
  15961. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15962. // this.resetTextureCache();
  15963. texture.isReady = true;
  15964. };
  15965. /**
  15966. * Creates a new raw cube texture
  15967. * @param data defines the array of data to use to create each face
  15968. * @param size defines the size of the textures
  15969. * @param format defines the format of the data
  15970. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15971. * @param generateMipMaps defines if the engine should generate the mip levels
  15972. * @param invertY defines if data must be stored with Y axis inverted
  15973. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15974. * @param compression defines the compression used (null by default)
  15975. * @returns the cube texture as an InternalTexture
  15976. */
  15977. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15978. if (compression === void 0) { compression = null; }
  15979. var gl = this._gl;
  15980. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15981. texture.isCube = true;
  15982. texture.generateMipMaps = generateMipMaps;
  15983. texture.format = format;
  15984. texture.type = type;
  15985. if (!this._doNotHandleContextLost) {
  15986. texture._bufferViewArray = data;
  15987. }
  15988. var textureType = this._getWebGLTextureType(type);
  15989. var internalFormat = this._getInternalFormat(format);
  15990. if (internalFormat === gl.RGB) {
  15991. internalFormat = gl.RGBA;
  15992. }
  15993. var width = size;
  15994. var height = width;
  15995. texture.width = width;
  15996. texture.height = height;
  15997. // Double check on POT to generate Mips.
  15998. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15999. if (!isPot) {
  16000. generateMipMaps = false;
  16001. }
  16002. // Upload data if needed. The texture won't be ready until then.
  16003. if (data) {
  16004. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16005. }
  16006. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16007. // Filters
  16008. if (data && generateMipMaps) {
  16009. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16010. }
  16011. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16012. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16013. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16014. }
  16015. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16016. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16017. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16018. }
  16019. else {
  16020. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16021. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16022. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16023. }
  16024. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16025. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16026. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16027. return texture;
  16028. };
  16029. /**
  16030. * Creates a new raw cube texture from a specified url
  16031. * @param url defines the url where the data is located
  16032. * @param scene defines the current scene
  16033. * @param size defines the size of the textures
  16034. * @param format defines the format of the data
  16035. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16036. * @param noMipmap defines if the engine should avoid generating the mip levels
  16037. * @param callback defines a callback used to extract texture data from loaded data
  16038. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16039. * @param onLoad defines a callback called when texture is loaded
  16040. * @param onError defines a callback called if there is an error
  16041. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16042. * @param invertY defines if data must be stored with Y axis inverted
  16043. * @returns the cube texture as an InternalTexture
  16044. */
  16045. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16046. var _this = this;
  16047. if (onLoad === void 0) { onLoad = null; }
  16048. if (onError === void 0) { onError = null; }
  16049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16050. if (invertY === void 0) { invertY = false; }
  16051. var gl = this._gl;
  16052. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16053. scene._addPendingData(texture);
  16054. texture.url = url;
  16055. this._internalTexturesCache.push(texture);
  16056. var onerror = function (request, exception) {
  16057. scene._removePendingData(texture);
  16058. if (onError && request) {
  16059. onError(request.status + " " + request.statusText, exception);
  16060. }
  16061. };
  16062. var internalCallback = function (data) {
  16063. var width = texture.width;
  16064. var faceDataArrays = callback(data);
  16065. if (!faceDataArrays) {
  16066. return;
  16067. }
  16068. if (mipmapGenerator) {
  16069. var textureType = _this._getWebGLTextureType(type);
  16070. var internalFormat = _this._getInternalFormat(format);
  16071. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16072. var needConversion = false;
  16073. if (internalFormat === gl.RGB) {
  16074. internalFormat = gl.RGBA;
  16075. needConversion = true;
  16076. }
  16077. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16078. _this._unpackFlipY(false);
  16079. var mipData = mipmapGenerator(faceDataArrays);
  16080. for (var level = 0; level < mipData.length; level++) {
  16081. var mipSize = width >> level;
  16082. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16083. var mipFaceData = mipData[level][faceIndex];
  16084. if (needConversion) {
  16085. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16086. }
  16087. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16088. }
  16089. }
  16090. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16091. }
  16092. else {
  16093. texture.generateMipMaps = !noMipmap;
  16094. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16095. }
  16096. texture.isReady = true;
  16097. // this.resetTextureCache();
  16098. scene._removePendingData(texture);
  16099. if (onLoad) {
  16100. onLoad();
  16101. }
  16102. };
  16103. this._loadFile(url, function (data) {
  16104. internalCallback(data);
  16105. }, undefined, scene.database, true, onerror);
  16106. return texture;
  16107. };
  16108. ;
  16109. /**
  16110. * Update a raw 3D texture
  16111. * @param texture defines the texture to update
  16112. * @param data defines the data to store
  16113. * @param format defines the data format
  16114. * @param invertY defines if data must be stored with Y axis inverted
  16115. * @param compression defines the used compression (can be null)
  16116. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16117. */
  16118. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16119. if (compression === void 0) { compression = null; }
  16120. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16121. var internalType = this._getWebGLTextureType(textureType);
  16122. var internalFormat = this._getInternalFormat(format);
  16123. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16124. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16125. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16126. if (!this._doNotHandleContextLost) {
  16127. texture._bufferView = data;
  16128. texture.format = format;
  16129. texture.invertY = invertY;
  16130. texture._compression = compression;
  16131. }
  16132. if (texture.width % 4 !== 0) {
  16133. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16134. }
  16135. if (compression && data) {
  16136. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16137. }
  16138. else {
  16139. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16140. }
  16141. if (texture.generateMipMaps) {
  16142. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16143. }
  16144. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16145. // this.resetTextureCache();
  16146. texture.isReady = true;
  16147. };
  16148. /**
  16149. * Creates a new raw 3D texture
  16150. * @param data defines the data used to create the texture
  16151. * @param width defines the width of the texture
  16152. * @param height defines the height of the texture
  16153. * @param depth defines the depth of the texture
  16154. * @param format defines the format of the texture
  16155. * @param generateMipMaps defines if the engine must generate mip levels
  16156. * @param invertY defines if data must be stored with Y axis inverted
  16157. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16158. * @param compression defines the compressed used (can be null)
  16159. * @param textureType defines the compressed used (can be null)
  16160. * @returns a new raw 3D texture (stored in an InternalTexture)
  16161. */
  16162. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16163. if (compression === void 0) { compression = null; }
  16164. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16165. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16166. texture.baseWidth = width;
  16167. texture.baseHeight = height;
  16168. texture.baseDepth = depth;
  16169. texture.width = width;
  16170. texture.height = height;
  16171. texture.depth = depth;
  16172. texture.format = format;
  16173. texture.type = textureType;
  16174. texture.generateMipMaps = generateMipMaps;
  16175. texture.samplingMode = samplingMode;
  16176. texture.is3D = true;
  16177. if (!this._doNotHandleContextLost) {
  16178. texture._bufferView = data;
  16179. }
  16180. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16181. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16182. // Filters
  16183. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16184. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16185. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16186. if (generateMipMaps) {
  16187. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16188. }
  16189. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16190. this._internalTexturesCache.push(texture);
  16191. return texture;
  16192. };
  16193. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16194. var gl = this._gl;
  16195. if (!gl) {
  16196. return;
  16197. }
  16198. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16199. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16200. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16201. if (!noMipmap && !isCompressed) {
  16202. gl.generateMipmap(gl.TEXTURE_2D);
  16203. }
  16204. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16205. // this.resetTextureCache();
  16206. if (scene) {
  16207. scene._removePendingData(texture);
  16208. }
  16209. texture.onLoadedObservable.notifyObservers(texture);
  16210. texture.onLoadedObservable.clear();
  16211. };
  16212. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16213. var _this = this;
  16214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16215. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16216. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16217. var gl = this._gl;
  16218. if (!gl) {
  16219. return;
  16220. }
  16221. if (!texture._webGLTexture) {
  16222. // this.resetTextureCache();
  16223. if (scene) {
  16224. scene._removePendingData(texture);
  16225. }
  16226. return;
  16227. }
  16228. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16229. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16230. texture.baseWidth = width;
  16231. texture.baseHeight = height;
  16232. texture.width = potWidth;
  16233. texture.height = potHeight;
  16234. texture.isReady = true;
  16235. if (processFunction(potWidth, potHeight, function () {
  16236. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16237. })) {
  16238. // Returning as texture needs extra async steps
  16239. return;
  16240. }
  16241. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16242. };
  16243. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16244. // Create new RGBA data container.
  16245. var rgbaData;
  16246. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16247. rgbaData = new Float32Array(width * height * 4);
  16248. }
  16249. else {
  16250. rgbaData = new Uint32Array(width * height * 4);
  16251. }
  16252. // Convert each pixel.
  16253. for (var x = 0; x < width; x++) {
  16254. for (var y = 0; y < height; y++) {
  16255. var index = (y * width + x) * 3;
  16256. var newIndex = (y * width + x) * 4;
  16257. // Map Old Value to new value.
  16258. rgbaData[newIndex + 0] = rgbData[index + 0];
  16259. rgbaData[newIndex + 1] = rgbData[index + 1];
  16260. rgbaData[newIndex + 2] = rgbData[index + 2];
  16261. // Add fully opaque alpha channel.
  16262. rgbaData[newIndex + 3] = 1;
  16263. }
  16264. }
  16265. return rgbaData;
  16266. };
  16267. /** @hidden */
  16268. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16269. var gl = this._gl;
  16270. if (texture._framebuffer) {
  16271. gl.deleteFramebuffer(texture._framebuffer);
  16272. texture._framebuffer = null;
  16273. }
  16274. if (texture._depthStencilBuffer) {
  16275. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16276. texture._depthStencilBuffer = null;
  16277. }
  16278. if (texture._MSAAFramebuffer) {
  16279. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16280. texture._MSAAFramebuffer = null;
  16281. }
  16282. if (texture._MSAARenderBuffer) {
  16283. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16284. texture._MSAARenderBuffer = null;
  16285. }
  16286. };
  16287. /** @hidden */
  16288. Engine.prototype._releaseTexture = function (texture) {
  16289. var gl = this._gl;
  16290. this._releaseFramebufferObjects(texture);
  16291. gl.deleteTexture(texture._webGLTexture);
  16292. // Unbind channels
  16293. this.unbindAllTextures();
  16294. var index = this._internalTexturesCache.indexOf(texture);
  16295. if (index !== -1) {
  16296. this._internalTexturesCache.splice(index, 1);
  16297. }
  16298. // Integrated fixed lod samplers.
  16299. if (texture._lodTextureHigh) {
  16300. texture._lodTextureHigh.dispose();
  16301. }
  16302. if (texture._lodTextureMid) {
  16303. texture._lodTextureMid.dispose();
  16304. }
  16305. if (texture._lodTextureLow) {
  16306. texture._lodTextureLow.dispose();
  16307. }
  16308. // Set output texture of post process to null if the texture has been released/disposed
  16309. this.scenes.forEach(function (scene) {
  16310. scene.postProcesses.forEach(function (postProcess) {
  16311. if (postProcess._outputTexture == texture) {
  16312. postProcess._outputTexture = null;
  16313. }
  16314. });
  16315. scene.cameras.forEach(function (camera) {
  16316. camera._postProcesses.forEach(function (postProcess) {
  16317. if (postProcess) {
  16318. if (postProcess._outputTexture == texture) {
  16319. postProcess._outputTexture = null;
  16320. }
  16321. }
  16322. });
  16323. });
  16324. });
  16325. };
  16326. Engine.prototype.setProgram = function (program) {
  16327. if (this._currentProgram !== program) {
  16328. this._gl.useProgram(program);
  16329. this._currentProgram = program;
  16330. }
  16331. };
  16332. /**
  16333. * Binds an effect to the webGL context
  16334. * @param effect defines the effect to bind
  16335. */
  16336. Engine.prototype.bindSamplers = function (effect) {
  16337. this.setProgram(effect.getProgram());
  16338. var samplers = effect.getSamplers();
  16339. for (var index = 0; index < samplers.length; index++) {
  16340. var uniform = effect.getUniform(samplers[index]);
  16341. if (uniform) {
  16342. this._boundUniforms[index] = uniform;
  16343. }
  16344. }
  16345. this._currentEffect = null;
  16346. };
  16347. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16348. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16349. return;
  16350. }
  16351. // Remove
  16352. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16353. // Bind last to it
  16354. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16355. // Bind to dummy
  16356. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16357. };
  16358. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16359. if (!internalTexture) {
  16360. return -1;
  16361. }
  16362. internalTexture._initialSlot = channel;
  16363. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16364. if (channel !== internalTexture._designatedSlot) {
  16365. this._textureCollisions.addCount(1, false);
  16366. }
  16367. }
  16368. else {
  16369. if (channel !== internalTexture._designatedSlot) {
  16370. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16371. return internalTexture._designatedSlot;
  16372. }
  16373. else {
  16374. // No slot for this texture, let's pick a new one (if we find a free slot)
  16375. if (this._nextFreeTextureSlots.length) {
  16376. return this._nextFreeTextureSlots[0];
  16377. }
  16378. // We need to recycle the oldest bound texture, sorry.
  16379. this._textureCollisions.addCount(1, false);
  16380. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16381. }
  16382. }
  16383. }
  16384. return channel;
  16385. };
  16386. Engine.prototype._linkTrackers = function (previous, next) {
  16387. previous.next = next;
  16388. next.previous = previous;
  16389. };
  16390. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16391. var currentSlot = internalTexture._designatedSlot;
  16392. if (currentSlot === -1) {
  16393. return -1;
  16394. }
  16395. internalTexture._designatedSlot = -1;
  16396. if (this.disableTextureBindingOptimization) {
  16397. return -1;
  16398. }
  16399. // Remove from bound list
  16400. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16401. // Free the slot
  16402. this._boundTexturesCache[currentSlot] = null;
  16403. this._nextFreeTextureSlots.push(currentSlot);
  16404. return currentSlot;
  16405. };
  16406. Engine.prototype._activateCurrentTexture = function () {
  16407. if (this._currentTextureChannel !== this._activeChannel) {
  16408. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16409. this._currentTextureChannel = this._activeChannel;
  16410. }
  16411. };
  16412. /** @hidden */
  16413. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16414. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16415. if (force === void 0) { force = false; }
  16416. var wasPreviouslyBound = false;
  16417. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16418. this._activeChannel = texture._designatedSlot;
  16419. }
  16420. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16421. var isTextureForRendering = texture && texture._initialSlot > -1;
  16422. if (currentTextureBound !== texture || force) {
  16423. if (currentTextureBound) {
  16424. this._removeDesignatedSlot(currentTextureBound);
  16425. }
  16426. this._activateCurrentTexture();
  16427. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16428. this._boundTexturesCache[this._activeChannel] = texture;
  16429. if (texture) {
  16430. if (!this.disableTextureBindingOptimization) {
  16431. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16432. if (slotIndex > -1) {
  16433. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16434. }
  16435. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16436. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16437. }
  16438. texture._designatedSlot = this._activeChannel;
  16439. }
  16440. }
  16441. else if (forTextureDataUpdate) {
  16442. wasPreviouslyBound = true;
  16443. this._activateCurrentTexture();
  16444. }
  16445. if (isTextureForRendering && !forTextureDataUpdate) {
  16446. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16447. }
  16448. return wasPreviouslyBound;
  16449. };
  16450. /** @hidden */
  16451. Engine.prototype._bindTexture = function (channel, texture) {
  16452. if (channel < 0) {
  16453. return;
  16454. }
  16455. if (texture) {
  16456. channel = this._getCorrectTextureChannel(channel, texture);
  16457. }
  16458. this._activeChannel = channel;
  16459. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16460. };
  16461. /**
  16462. * Sets a texture to the webGL context from a postprocess
  16463. * @param channel defines the channel to use
  16464. * @param postProcess defines the source postprocess
  16465. */
  16466. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16467. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16468. };
  16469. /**
  16470. * Binds the output of the passed in post process to the texture channel specified
  16471. * @param channel The channel the texture should be bound to
  16472. * @param postProcess The post process which's output should be bound
  16473. */
  16474. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16475. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16476. };
  16477. /**
  16478. * Unbind all textures from the webGL context
  16479. */
  16480. Engine.prototype.unbindAllTextures = function () {
  16481. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16482. this._activeChannel = channel;
  16483. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16484. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16485. if (this.webGLVersion > 1) {
  16486. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16487. }
  16488. }
  16489. };
  16490. /**
  16491. * Sets a texture to the according uniform.
  16492. * @param channel The texture channel
  16493. * @param uniform The uniform to set
  16494. * @param texture The texture to apply
  16495. */
  16496. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16497. if (channel < 0) {
  16498. return;
  16499. }
  16500. if (uniform) {
  16501. this._boundUniforms[channel] = uniform;
  16502. }
  16503. this._setTexture(channel, texture);
  16504. };
  16505. /**
  16506. * Sets a depth stencil texture from a render target to the according uniform.
  16507. * @param channel The texture channel
  16508. * @param uniform The uniform to set
  16509. * @param texture The render target texture containing the depth stencil texture to apply
  16510. */
  16511. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16512. if (channel < 0) {
  16513. return;
  16514. }
  16515. if (uniform) {
  16516. this._boundUniforms[channel] = uniform;
  16517. }
  16518. if (!texture || !texture.depthStencilTexture) {
  16519. this._setTexture(channel, null);
  16520. }
  16521. else {
  16522. this._setTexture(channel, texture, false, true);
  16523. }
  16524. };
  16525. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16526. var uniform = this._boundUniforms[sourceSlot];
  16527. if (uniform._currentState === destination) {
  16528. return;
  16529. }
  16530. this._gl.uniform1i(uniform, destination);
  16531. uniform._currentState = destination;
  16532. };
  16533. Engine.prototype._getTextureWrapMode = function (mode) {
  16534. switch (mode) {
  16535. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16536. return this._gl.REPEAT;
  16537. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16538. return this._gl.CLAMP_TO_EDGE;
  16539. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16540. return this._gl.MIRRORED_REPEAT;
  16541. }
  16542. return this._gl.REPEAT;
  16543. };
  16544. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16545. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16546. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16547. // Not ready?
  16548. if (!texture) {
  16549. if (this._boundTexturesCache[channel] != null) {
  16550. this._activeChannel = channel;
  16551. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16553. if (this.webGLVersion > 1) {
  16554. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16555. }
  16556. }
  16557. return false;
  16558. }
  16559. // Video
  16560. if (texture.video) {
  16561. this._activeChannel = channel;
  16562. texture.update();
  16563. }
  16564. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16565. texture.delayLoad();
  16566. return false;
  16567. }
  16568. var internalTexture;
  16569. if (depthStencilTexture) {
  16570. internalTexture = texture.depthStencilTexture;
  16571. }
  16572. else if (texture.isReady()) {
  16573. internalTexture = texture.getInternalTexture();
  16574. }
  16575. else if (texture.isCube) {
  16576. internalTexture = this.emptyCubeTexture;
  16577. }
  16578. else if (texture.is3D) {
  16579. internalTexture = this.emptyTexture3D;
  16580. }
  16581. else {
  16582. internalTexture = this.emptyTexture;
  16583. }
  16584. if (!isPartOfTextureArray) {
  16585. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16586. }
  16587. var needToBind = true;
  16588. if (this._boundTexturesCache[channel] === internalTexture) {
  16589. this._moveBoundTextureOnTop(internalTexture);
  16590. if (!isPartOfTextureArray) {
  16591. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16592. }
  16593. needToBind = false;
  16594. }
  16595. this._activeChannel = channel;
  16596. if (internalTexture && internalTexture.is3D) {
  16597. if (needToBind) {
  16598. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16599. }
  16600. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16601. internalTexture._cachedWrapU = texture.wrapU;
  16602. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16603. }
  16604. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16605. internalTexture._cachedWrapV = texture.wrapV;
  16606. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16607. }
  16608. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16609. internalTexture._cachedWrapR = texture.wrapR;
  16610. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16611. }
  16612. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16613. }
  16614. else if (internalTexture && internalTexture.isCube) {
  16615. if (needToBind) {
  16616. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16617. }
  16618. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16619. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16620. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16621. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16622. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16623. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16624. }
  16625. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16626. }
  16627. else {
  16628. if (needToBind) {
  16629. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16630. }
  16631. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16632. internalTexture._cachedWrapU = texture.wrapU;
  16633. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16634. }
  16635. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16636. internalTexture._cachedWrapV = texture.wrapV;
  16637. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16638. }
  16639. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16640. }
  16641. return true;
  16642. };
  16643. /**
  16644. * Sets an array of texture to the webGL context
  16645. * @param channel defines the channel where the texture array must be set
  16646. * @param uniform defines the associated uniform location
  16647. * @param textures defines the array of textures to bind
  16648. */
  16649. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16650. if (channel < 0 || !uniform) {
  16651. return;
  16652. }
  16653. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16654. this._textureUnits = new Int32Array(textures.length);
  16655. }
  16656. for (var i = 0; i < textures.length; i++) {
  16657. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16658. }
  16659. this._gl.uniform1iv(uniform, this._textureUnits);
  16660. for (var index = 0; index < textures.length; index++) {
  16661. this._setTexture(this._textureUnits[index], textures[index], true);
  16662. }
  16663. };
  16664. /** @hidden */
  16665. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16666. var internalTexture = texture.getInternalTexture();
  16667. if (!internalTexture) {
  16668. return;
  16669. }
  16670. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16671. var value = texture.anisotropicFilteringLevel;
  16672. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16673. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16674. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16675. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16676. }
  16677. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16678. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16679. internalTexture._cachedAnisotropicFilteringLevel = value;
  16680. }
  16681. };
  16682. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16683. this._bindTextureDirectly(target, texture, true, true);
  16684. this._gl.texParameterf(target, parameter, value);
  16685. };
  16686. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16687. if (texture) {
  16688. this._bindTextureDirectly(target, texture, true, true);
  16689. }
  16690. this._gl.texParameteri(target, parameter, value);
  16691. };
  16692. /**
  16693. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16694. * @param x defines the x coordinate of the rectangle where pixels must be read
  16695. * @param y defines the y coordinate of the rectangle where pixels must be read
  16696. * @param width defines the width of the rectangle where pixels must be read
  16697. * @param height defines the height of the rectangle where pixels must be read
  16698. * @returns a Uint8Array containing RGBA colors
  16699. */
  16700. Engine.prototype.readPixels = function (x, y, width, height) {
  16701. var data = new Uint8Array(height * width * 4);
  16702. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16703. return data;
  16704. };
  16705. /**
  16706. * Add an externaly attached data from its key.
  16707. * This method call will fail and return false, if such key already exists.
  16708. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16709. * @param key the unique key that identifies the data
  16710. * @param data the data object to associate to the key for this Engine instance
  16711. * @return true if no such key were already present and the data was added successfully, false otherwise
  16712. */
  16713. Engine.prototype.addExternalData = function (key, data) {
  16714. if (!this._externalData) {
  16715. this._externalData = new BABYLON.StringDictionary();
  16716. }
  16717. return this._externalData.add(key, data);
  16718. };
  16719. /**
  16720. * Get an externaly attached data from its key
  16721. * @param key the unique key that identifies the data
  16722. * @return the associated data, if present (can be null), or undefined if not present
  16723. */
  16724. Engine.prototype.getExternalData = function (key) {
  16725. if (!this._externalData) {
  16726. this._externalData = new BABYLON.StringDictionary();
  16727. }
  16728. return this._externalData.get(key);
  16729. };
  16730. /**
  16731. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16732. * @param key the unique key that identifies the data
  16733. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16734. * @return the associated data, can be null if the factory returned null.
  16735. */
  16736. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16737. if (!this._externalData) {
  16738. this._externalData = new BABYLON.StringDictionary();
  16739. }
  16740. return this._externalData.getOrAddWithFactory(key, factory);
  16741. };
  16742. /**
  16743. * Remove an externaly attached data from the Engine instance
  16744. * @param key the unique key that identifies the data
  16745. * @return true if the data was successfully removed, false if it doesn't exist
  16746. */
  16747. Engine.prototype.removeExternalData = function (key) {
  16748. if (!this._externalData) {
  16749. this._externalData = new BABYLON.StringDictionary();
  16750. }
  16751. return this._externalData.remove(key);
  16752. };
  16753. /**
  16754. * Unbind all vertex attributes from the webGL context
  16755. */
  16756. Engine.prototype.unbindAllAttributes = function () {
  16757. if (this._mustWipeVertexAttributes) {
  16758. this._mustWipeVertexAttributes = false;
  16759. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16760. this._gl.disableVertexAttribArray(i);
  16761. this._vertexAttribArraysEnabled[i] = false;
  16762. this._currentBufferPointers[i].active = false;
  16763. }
  16764. return;
  16765. }
  16766. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16767. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16768. continue;
  16769. }
  16770. this._gl.disableVertexAttribArray(i);
  16771. this._vertexAttribArraysEnabled[i] = false;
  16772. this._currentBufferPointers[i].active = false;
  16773. }
  16774. };
  16775. /**
  16776. * 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
  16777. */
  16778. Engine.prototype.releaseEffects = function () {
  16779. for (var name in this._compiledEffects) {
  16780. this._deleteProgram(this._compiledEffects[name]._program);
  16781. }
  16782. this._compiledEffects = {};
  16783. };
  16784. /**
  16785. * Dispose and release all associated resources
  16786. */
  16787. Engine.prototype.dispose = function () {
  16788. this.hideLoadingUI();
  16789. this.stopRenderLoop();
  16790. // Release postProcesses
  16791. while (this.postProcesses.length) {
  16792. this.postProcesses[0].dispose();
  16793. }
  16794. // Empty texture
  16795. if (this._emptyTexture) {
  16796. this._releaseTexture(this._emptyTexture);
  16797. this._emptyTexture = null;
  16798. }
  16799. if (this._emptyCubeTexture) {
  16800. this._releaseTexture(this._emptyCubeTexture);
  16801. this._emptyCubeTexture = null;
  16802. }
  16803. // Rescale PP
  16804. if (this._rescalePostProcess) {
  16805. this._rescalePostProcess.dispose();
  16806. }
  16807. // Release scenes
  16808. while (this.scenes.length) {
  16809. this.scenes[0].dispose();
  16810. }
  16811. // Release audio engine
  16812. if (Engine.audioEngine) {
  16813. Engine.audioEngine.dispose();
  16814. }
  16815. // Release effects
  16816. this.releaseEffects();
  16817. // Unbind
  16818. this.unbindAllAttributes();
  16819. this._boundUniforms = [];
  16820. if (this._dummyFramebuffer) {
  16821. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16822. }
  16823. //WebVR
  16824. this.disableVR();
  16825. // Events
  16826. if (BABYLON.Tools.IsWindowObjectExist()) {
  16827. window.removeEventListener("blur", this._onBlur);
  16828. window.removeEventListener("focus", this._onFocus);
  16829. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16830. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16831. if (this._renderingCanvas) {
  16832. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16833. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16834. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16835. if (!this._doNotHandleContextLost) {
  16836. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16837. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16838. }
  16839. }
  16840. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16841. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16842. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16843. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16844. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16845. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16846. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16847. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16848. if (this._onVrDisplayConnect) {
  16849. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16850. if (this._onVrDisplayDisconnect) {
  16851. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16852. }
  16853. if (this._onVrDisplayPresentChange) {
  16854. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16855. }
  16856. this._onVrDisplayConnect = null;
  16857. this._onVrDisplayDisconnect = null;
  16858. }
  16859. }
  16860. // Remove from Instances
  16861. var index = Engine.Instances.indexOf(this);
  16862. if (index >= 0) {
  16863. Engine.Instances.splice(index, 1);
  16864. }
  16865. this._workingCanvas = null;
  16866. this._workingContext = null;
  16867. this._currentBufferPointers = [];
  16868. this._renderingCanvas = null;
  16869. this._currentProgram = null;
  16870. this._bindedRenderFunction = null;
  16871. this.onResizeObservable.clear();
  16872. this.onCanvasBlurObservable.clear();
  16873. this.onCanvasFocusObservable.clear();
  16874. this.onCanvasPointerOutObservable.clear();
  16875. this.onBeginFrameObservable.clear();
  16876. this.onEndFrameObservable.clear();
  16877. BABYLON.Effect.ResetCache();
  16878. // Abort active requests
  16879. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16880. var request = _a[_i];
  16881. request.abort();
  16882. }
  16883. };
  16884. // Loading screen
  16885. /**
  16886. * Display the loading screen
  16887. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16888. */
  16889. Engine.prototype.displayLoadingUI = function () {
  16890. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16891. return;
  16892. }
  16893. var loadingScreen = this.loadingScreen;
  16894. if (loadingScreen) {
  16895. loadingScreen.displayLoadingUI();
  16896. }
  16897. };
  16898. /**
  16899. * Hide the loading screen
  16900. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16901. */
  16902. Engine.prototype.hideLoadingUI = function () {
  16903. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16904. return;
  16905. }
  16906. var loadingScreen = this.loadingScreen;
  16907. if (loadingScreen) {
  16908. loadingScreen.hideLoadingUI();
  16909. }
  16910. };
  16911. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16912. /**
  16913. * Gets the current loading screen object
  16914. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16915. */
  16916. get: function () {
  16917. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16918. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16919. return this._loadingScreen;
  16920. },
  16921. /**
  16922. * Sets the current loading screen object
  16923. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16924. */
  16925. set: function (loadingScreen) {
  16926. this._loadingScreen = loadingScreen;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16932. /**
  16933. * Sets the current loading screen text
  16934. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16935. */
  16936. set: function (text) {
  16937. this.loadingScreen.loadingUIText = text;
  16938. },
  16939. enumerable: true,
  16940. configurable: true
  16941. });
  16942. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16943. /**
  16944. * Sets the current loading screen background color
  16945. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16946. */
  16947. set: function (color) {
  16948. this.loadingScreen.loadingUIBackgroundColor = color;
  16949. },
  16950. enumerable: true,
  16951. configurable: true
  16952. });
  16953. /**
  16954. * Attach a new callback raised when context lost event is fired
  16955. * @param callback defines the callback to call
  16956. */
  16957. Engine.prototype.attachContextLostEvent = function (callback) {
  16958. if (this._renderingCanvas) {
  16959. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16960. }
  16961. };
  16962. /**
  16963. * Attach a new callback raised when context restored event is fired
  16964. * @param callback defines the callback to call
  16965. */
  16966. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16967. if (this._renderingCanvas) {
  16968. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16969. }
  16970. };
  16971. /**
  16972. * Gets the source code of the vertex shader associated with a specific webGL program
  16973. * @param program defines the program to use
  16974. * @returns a string containing the source code of the vertex shader associated with the program
  16975. */
  16976. Engine.prototype.getVertexShaderSource = function (program) {
  16977. var shaders = this._gl.getAttachedShaders(program);
  16978. if (!shaders) {
  16979. return null;
  16980. }
  16981. return this._gl.getShaderSource(shaders[0]);
  16982. };
  16983. /**
  16984. * Gets the source code of the fragment shader associated with a specific webGL program
  16985. * @param program defines the program to use
  16986. * @returns a string containing the source code of the fragment shader associated with the program
  16987. */
  16988. Engine.prototype.getFragmentShaderSource = function (program) {
  16989. var shaders = this._gl.getAttachedShaders(program);
  16990. if (!shaders) {
  16991. return null;
  16992. }
  16993. return this._gl.getShaderSource(shaders[1]);
  16994. };
  16995. /**
  16996. * Get the current error code of the webGL context
  16997. * @returns the error code
  16998. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16999. */
  17000. Engine.prototype.getError = function () {
  17001. return this._gl.getError();
  17002. };
  17003. // FPS
  17004. /**
  17005. * Gets the current framerate
  17006. * @returns a number representing the framerate
  17007. */
  17008. Engine.prototype.getFps = function () {
  17009. return this._fps;
  17010. };
  17011. /**
  17012. * Gets the time spent between current and previous frame
  17013. * @returns a number representing the delta time in ms
  17014. */
  17015. Engine.prototype.getDeltaTime = function () {
  17016. return this._deltaTime;
  17017. };
  17018. Engine.prototype._measureFps = function () {
  17019. this._performanceMonitor.sampleFrame();
  17020. this._fps = this._performanceMonitor.averageFPS;
  17021. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17022. };
  17023. /** @hidden */
  17024. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17025. if (faceIndex === void 0) { faceIndex = -1; }
  17026. if (level === void 0) { level = 0; }
  17027. var gl = this._gl;
  17028. if (!this._dummyFramebuffer) {
  17029. var dummy = gl.createFramebuffer();
  17030. if (!dummy) {
  17031. throw new Error("Unable to create dummy framebuffer");
  17032. }
  17033. this._dummyFramebuffer = dummy;
  17034. }
  17035. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17036. if (faceIndex > -1) {
  17037. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17038. }
  17039. else {
  17040. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17041. }
  17042. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17043. var buffer;
  17044. switch (readType) {
  17045. case gl.UNSIGNED_BYTE:
  17046. buffer = new Uint8Array(4 * width * height);
  17047. readType = gl.UNSIGNED_BYTE;
  17048. break;
  17049. default:
  17050. buffer = new Float32Array(4 * width * height);
  17051. readType = gl.FLOAT;
  17052. break;
  17053. }
  17054. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17055. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17056. return buffer;
  17057. };
  17058. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17059. if (this._webGLVersion > 1) {
  17060. return this._caps.colorBufferFloat;
  17061. }
  17062. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17063. };
  17064. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17065. if (this._webGLVersion > 1) {
  17066. return this._caps.colorBufferFloat;
  17067. }
  17068. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17069. };
  17070. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17071. Engine.prototype._canRenderToFramebuffer = function (type) {
  17072. var gl = this._gl;
  17073. //clear existing errors
  17074. while (gl.getError() !== gl.NO_ERROR) { }
  17075. var successful = true;
  17076. var texture = gl.createTexture();
  17077. gl.bindTexture(gl.TEXTURE_2D, texture);
  17078. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17079. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17080. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17081. var fb = gl.createFramebuffer();
  17082. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17083. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17084. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17085. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17086. successful = successful && (gl.getError() === gl.NO_ERROR);
  17087. //try render by clearing frame buffer's color buffer
  17088. if (successful) {
  17089. gl.clear(gl.COLOR_BUFFER_BIT);
  17090. successful = successful && (gl.getError() === gl.NO_ERROR);
  17091. }
  17092. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17093. if (successful) {
  17094. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17095. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17096. var readFormat = gl.RGBA;
  17097. var readType = gl.UNSIGNED_BYTE;
  17098. var buffer = new Uint8Array(4);
  17099. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17100. successful = successful && (gl.getError() === gl.NO_ERROR);
  17101. }
  17102. //clean up
  17103. gl.deleteTexture(texture);
  17104. gl.deleteFramebuffer(fb);
  17105. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17106. //clear accumulated errors
  17107. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17108. return successful;
  17109. };
  17110. /** @hidden */
  17111. Engine.prototype._getWebGLTextureType = function (type) {
  17112. if (type === Engine.TEXTURETYPE_FLOAT) {
  17113. return this._gl.FLOAT;
  17114. }
  17115. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17116. // Add Half Float Constant.
  17117. return this._gl.HALF_FLOAT_OES;
  17118. }
  17119. return this._gl.UNSIGNED_BYTE;
  17120. };
  17121. ;
  17122. Engine.prototype._getInternalFormat = function (format) {
  17123. var internalFormat = this._gl.RGBA;
  17124. switch (format) {
  17125. case Engine.TEXTUREFORMAT_ALPHA:
  17126. internalFormat = this._gl.ALPHA;
  17127. break;
  17128. case Engine.TEXTUREFORMAT_LUMINANCE:
  17129. internalFormat = this._gl.LUMINANCE;
  17130. break;
  17131. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17132. internalFormat = this._gl.LUMINANCE_ALPHA;
  17133. break;
  17134. case Engine.TEXTUREFORMAT_RGB:
  17135. internalFormat = this._gl.RGB;
  17136. break;
  17137. case Engine.TEXTUREFORMAT_RGBA:
  17138. internalFormat = this._gl.RGBA;
  17139. break;
  17140. case Engine.TEXTUREFORMAT_R:
  17141. internalFormat = this._gl.RED;
  17142. break;
  17143. case Engine.TEXTUREFORMAT_RG:
  17144. internalFormat = this._gl.RG;
  17145. break;
  17146. }
  17147. return internalFormat;
  17148. };
  17149. /** @hidden */
  17150. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17151. if (this._webGLVersion === 1) {
  17152. if (format !== undefined) {
  17153. switch (format) {
  17154. case Engine.TEXTUREFORMAT_LUMINANCE:
  17155. return this._gl.LUMINANCE;
  17156. case Engine.TEXTUREFORMAT_ALPHA:
  17157. return this._gl.ALPHA;
  17158. }
  17159. }
  17160. return this._gl.RGBA;
  17161. }
  17162. if (type === Engine.TEXTURETYPE_FLOAT) {
  17163. if (format !== undefined) {
  17164. switch (format) {
  17165. case Engine.TEXTUREFORMAT_R:
  17166. return this._gl.R32F;
  17167. case Engine.TEXTUREFORMAT_RG:
  17168. return this._gl.RG32F;
  17169. case Engine.TEXTUREFORMAT_RGB:
  17170. return this._gl.RGB32F;
  17171. }
  17172. }
  17173. return this._gl.RGBA32F;
  17174. }
  17175. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17176. if (format) {
  17177. switch (format) {
  17178. case Engine.TEXTUREFORMAT_R:
  17179. return this._gl.R16F;
  17180. case Engine.TEXTUREFORMAT_RG:
  17181. return this._gl.RG16F;
  17182. case Engine.TEXTUREFORMAT_RGB:
  17183. return this._gl.RGB16F;
  17184. }
  17185. }
  17186. return this._gl.RGBA16F;
  17187. }
  17188. if (format !== undefined) {
  17189. switch (format) {
  17190. case Engine.TEXTUREFORMAT_LUMINANCE:
  17191. return this._gl.LUMINANCE;
  17192. case Engine.TEXTUREFORMAT_RGB:
  17193. return this._gl.RGB;
  17194. case Engine.TEXTUREFORMAT_R:
  17195. return this._gl.R8;
  17196. case Engine.TEXTUREFORMAT_RG:
  17197. return this._gl.RG8;
  17198. case Engine.TEXTUREFORMAT_ALPHA:
  17199. return this._gl.ALPHA;
  17200. }
  17201. }
  17202. return this._gl.RGBA;
  17203. };
  17204. ;
  17205. /** @hidden */
  17206. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17207. if (type === Engine.TEXTURETYPE_FLOAT) {
  17208. return this._gl.RGBA32F;
  17209. }
  17210. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17211. return this._gl.RGBA16F;
  17212. }
  17213. return this._gl.RGBA8;
  17214. };
  17215. ;
  17216. /**
  17217. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17218. * @return the new query
  17219. */
  17220. Engine.prototype.createQuery = function () {
  17221. return this._gl.createQuery();
  17222. };
  17223. /**
  17224. * Delete and release a webGL query
  17225. * @param query defines the query to delete
  17226. * @return the current engine
  17227. */
  17228. Engine.prototype.deleteQuery = function (query) {
  17229. this._gl.deleteQuery(query);
  17230. return this;
  17231. };
  17232. /**
  17233. * Check if a given query has resolved and got its value
  17234. * @param query defines the query to check
  17235. * @returns true if the query got its value
  17236. */
  17237. Engine.prototype.isQueryResultAvailable = function (query) {
  17238. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17239. };
  17240. /**
  17241. * Gets the value of a given query
  17242. * @param query defines the query to check
  17243. * @returns the value of the query
  17244. */
  17245. Engine.prototype.getQueryResult = function (query) {
  17246. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17247. };
  17248. /**
  17249. * Initiates an occlusion query
  17250. * @param algorithmType defines the algorithm to use
  17251. * @param query defines the query to use
  17252. * @returns the current engine
  17253. * @see http://doc.babylonjs.com/features/occlusionquery
  17254. */
  17255. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17256. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17257. this._gl.beginQuery(glAlgorithm, query);
  17258. return this;
  17259. };
  17260. /**
  17261. * Ends an occlusion query
  17262. * @see http://doc.babylonjs.com/features/occlusionquery
  17263. * @param algorithmType defines the algorithm to use
  17264. * @returns the current engine
  17265. */
  17266. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17267. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17268. this._gl.endQuery(glAlgorithm);
  17269. return this;
  17270. };
  17271. /* Time queries */
  17272. Engine.prototype._createTimeQuery = function () {
  17273. var timerQuery = this._caps.timerQuery;
  17274. if (timerQuery.createQueryEXT) {
  17275. return timerQuery.createQueryEXT();
  17276. }
  17277. return this.createQuery();
  17278. };
  17279. Engine.prototype._deleteTimeQuery = function (query) {
  17280. var timerQuery = this._caps.timerQuery;
  17281. if (timerQuery.deleteQueryEXT) {
  17282. timerQuery.deleteQueryEXT(query);
  17283. return;
  17284. }
  17285. this.deleteQuery(query);
  17286. };
  17287. Engine.prototype._getTimeQueryResult = function (query) {
  17288. var timerQuery = this._caps.timerQuery;
  17289. if (timerQuery.getQueryObjectEXT) {
  17290. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17291. }
  17292. return this.getQueryResult(query);
  17293. };
  17294. Engine.prototype._getTimeQueryAvailability = function (query) {
  17295. var timerQuery = this._caps.timerQuery;
  17296. if (timerQuery.getQueryObjectEXT) {
  17297. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17298. }
  17299. return this.isQueryResultAvailable(query);
  17300. };
  17301. /**
  17302. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17303. * Please note that only one query can be issued at a time
  17304. * @returns a time token used to track the time span
  17305. */
  17306. Engine.prototype.startTimeQuery = function () {
  17307. var timerQuery = this._caps.timerQuery;
  17308. if (!timerQuery) {
  17309. return null;
  17310. }
  17311. var token = new BABYLON._TimeToken();
  17312. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17313. if (this._caps.canUseTimestampForTimerQuery) {
  17314. token._startTimeQuery = this._createTimeQuery();
  17315. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17316. }
  17317. else {
  17318. if (this._currentNonTimestampToken) {
  17319. return this._currentNonTimestampToken;
  17320. }
  17321. token._timeElapsedQuery = this._createTimeQuery();
  17322. if (timerQuery.beginQueryEXT) {
  17323. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17324. }
  17325. else {
  17326. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17327. }
  17328. this._currentNonTimestampToken = token;
  17329. }
  17330. return token;
  17331. };
  17332. /**
  17333. * Ends a time query
  17334. * @param token defines the token used to measure the time span
  17335. * @returns the time spent (in ns)
  17336. */
  17337. Engine.prototype.endTimeQuery = function (token) {
  17338. var timerQuery = this._caps.timerQuery;
  17339. if (!timerQuery || !token) {
  17340. return -1;
  17341. }
  17342. if (this._caps.canUseTimestampForTimerQuery) {
  17343. if (!token._startTimeQuery) {
  17344. return -1;
  17345. }
  17346. if (!token._endTimeQuery) {
  17347. token._endTimeQuery = this._createTimeQuery();
  17348. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17349. }
  17350. }
  17351. else if (!token._timeElapsedQueryEnded) {
  17352. if (!token._timeElapsedQuery) {
  17353. return -1;
  17354. }
  17355. if (timerQuery.endQueryEXT) {
  17356. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17357. }
  17358. else {
  17359. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17360. }
  17361. token._timeElapsedQueryEnded = true;
  17362. }
  17363. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17364. var available = false;
  17365. if (token._endTimeQuery) {
  17366. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17367. }
  17368. else if (token._timeElapsedQuery) {
  17369. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17370. }
  17371. if (available && !disjoint) {
  17372. var result = 0;
  17373. if (this._caps.canUseTimestampForTimerQuery) {
  17374. if (!token._startTimeQuery || !token._endTimeQuery) {
  17375. return -1;
  17376. }
  17377. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17378. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17379. result = timeEnd - timeStart;
  17380. this._deleteTimeQuery(token._startTimeQuery);
  17381. this._deleteTimeQuery(token._endTimeQuery);
  17382. token._startTimeQuery = null;
  17383. token._endTimeQuery = null;
  17384. }
  17385. else {
  17386. if (!token._timeElapsedQuery) {
  17387. return -1;
  17388. }
  17389. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17390. this._deleteTimeQuery(token._timeElapsedQuery);
  17391. token._timeElapsedQuery = null;
  17392. token._timeElapsedQueryEnded = false;
  17393. this._currentNonTimestampToken = null;
  17394. }
  17395. return result;
  17396. }
  17397. return -1;
  17398. };
  17399. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17400. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17401. };
  17402. // Transform feedback
  17403. /**
  17404. * Creates a webGL transform feedback object
  17405. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17406. * @returns the webGL transform feedback object
  17407. */
  17408. Engine.prototype.createTransformFeedback = function () {
  17409. return this._gl.createTransformFeedback();
  17410. };
  17411. /**
  17412. * Delete a webGL transform feedback object
  17413. * @param value defines the webGL transform feedback object to delete
  17414. */
  17415. Engine.prototype.deleteTransformFeedback = function (value) {
  17416. this._gl.deleteTransformFeedback(value);
  17417. };
  17418. /**
  17419. * Bind a webGL transform feedback object to the webgl context
  17420. * @param value defines the webGL transform feedback object to bind
  17421. */
  17422. Engine.prototype.bindTransformFeedback = function (value) {
  17423. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17424. };
  17425. /**
  17426. * Begins a transform feedback operation
  17427. * @param usePoints defines if points or triangles must be used
  17428. */
  17429. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17430. if (usePoints === void 0) { usePoints = true; }
  17431. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17432. };
  17433. /**
  17434. * Ends a transform feedback operation
  17435. */
  17436. Engine.prototype.endTransformFeedback = function () {
  17437. this._gl.endTransformFeedback();
  17438. };
  17439. /**
  17440. * Specify the varyings to use with transform feedback
  17441. * @param program defines the associated webGL program
  17442. * @param value defines the list of strings representing the varying names
  17443. */
  17444. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17445. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17446. };
  17447. /**
  17448. * Bind a webGL buffer for a transform feedback operation
  17449. * @param value defines the webGL buffer to bind
  17450. */
  17451. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17452. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17453. };
  17454. /** @hidden */
  17455. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17456. var _this = this;
  17457. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17458. this._activeRequests.push(request);
  17459. request.onCompleteObservable.add(function (request) {
  17460. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17461. });
  17462. return request;
  17463. };
  17464. /** @hidden */
  17465. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17466. var _this = this;
  17467. return new Promise(function (resolve, reject) {
  17468. _this._loadFile(url, function (data) {
  17469. resolve(data);
  17470. }, undefined, database, useArrayBuffer, function (request, exception) {
  17471. reject(exception);
  17472. });
  17473. });
  17474. };
  17475. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17476. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17477. var onload = function (data) {
  17478. loadedFiles[index] = data;
  17479. loadedFiles._internalCount++;
  17480. if (loadedFiles._internalCount === 6) {
  17481. onfinish(loadedFiles);
  17482. }
  17483. };
  17484. var onerror = function (request, exception) {
  17485. if (onErrorCallBack && request) {
  17486. onErrorCallBack(request.status + " " + request.statusText, exception);
  17487. }
  17488. };
  17489. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17490. };
  17491. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17492. if (onError === void 0) { onError = null; }
  17493. var loadedFiles = [];
  17494. loadedFiles._internalCount = 0;
  17495. for (var index = 0; index < 6; index++) {
  17496. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17497. }
  17498. };
  17499. // Statics
  17500. /**
  17501. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17502. * @returns true if the engine can be created
  17503. * @ignorenaming
  17504. */
  17505. Engine.isSupported = function () {
  17506. try {
  17507. var tempcanvas = document.createElement("canvas");
  17508. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17509. return gl != null && !!window.WebGLRenderingContext;
  17510. }
  17511. catch (e) {
  17512. return false;
  17513. }
  17514. };
  17515. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17516. Engine.ExceptionList = [
  17517. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17518. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17519. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17520. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17521. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17522. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17523. ];
  17524. /** Gets the list of created engines */
  17525. Engine.Instances = new Array();
  17526. // Const statics
  17527. Engine._ALPHA_DISABLE = 0;
  17528. Engine._ALPHA_ADD = 1;
  17529. Engine._ALPHA_COMBINE = 2;
  17530. Engine._ALPHA_SUBTRACT = 3;
  17531. Engine._ALPHA_MULTIPLY = 4;
  17532. Engine._ALPHA_MAXIMIZED = 5;
  17533. Engine._ALPHA_ONEONE = 6;
  17534. Engine._ALPHA_PREMULTIPLIED = 7;
  17535. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17536. Engine._ALPHA_INTERPOLATE = 9;
  17537. Engine._ALPHA_SCREENMODE = 10;
  17538. Engine._DELAYLOADSTATE_NONE = 0;
  17539. Engine._DELAYLOADSTATE_LOADED = 1;
  17540. Engine._DELAYLOADSTATE_LOADING = 2;
  17541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17542. Engine._TEXTUREFORMAT_ALPHA = 0;
  17543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17545. Engine._TEXTUREFORMAT_RGB = 4;
  17546. Engine._TEXTUREFORMAT_RGBA = 5;
  17547. Engine._TEXTUREFORMAT_R = 6;
  17548. Engine._TEXTUREFORMAT_RG = 7;
  17549. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17550. Engine._TEXTURETYPE_FLOAT = 1;
  17551. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17552. // Depht or Stencil test Constants.
  17553. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17554. Engine._ALWAYS = 0x0207; // 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.
  17555. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17556. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17557. Engine._LEQUAL = 0x0203; // 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.
  17558. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17559. Engine._GEQUAL = 0x0206; // 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.
  17560. Engine._NOTEQUAL = 0x0205; // 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.
  17561. // Stencil Actions Constants.
  17562. Engine._KEEP = 0x1E00;
  17563. Engine._REPLACE = 0x1E01;
  17564. Engine._INCR = 0x1E02;
  17565. Engine._DECR = 0x1E03;
  17566. Engine._INVERT = 0x150A;
  17567. Engine._INCR_WRAP = 0x8507;
  17568. Engine._DECR_WRAP = 0x8508;
  17569. // Texture rescaling mode
  17570. Engine._SCALEMODE_FLOOR = 1;
  17571. Engine._SCALEMODE_NEAREST = 2;
  17572. Engine._SCALEMODE_CEILING = 3;
  17573. // Updatable statics so stick with vars here
  17574. /**
  17575. * Gets or sets the epsilon value used by collision engine
  17576. */
  17577. Engine.CollisionsEpsilon = 0.001;
  17578. /**
  17579. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17580. */
  17581. Engine.CodeRepository = "src/";
  17582. /**
  17583. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17584. */
  17585. Engine.ShadersRepository = "src/Shaders/";
  17586. return Engine;
  17587. }());
  17588. BABYLON.Engine = Engine;
  17589. })(BABYLON || (BABYLON = {}));
  17590. //# sourceMappingURL=babylon.engine.js.map
  17591. var BABYLON;
  17592. (function (BABYLON) {
  17593. /**
  17594. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17595. */
  17596. var Node = /** @class */ (function () {
  17597. /**
  17598. * Creates a new Node
  17599. * @param {string} name - the name and id to be given to this node
  17600. * @param {BABYLON.Scene} the scene this node will be added to
  17601. */
  17602. function Node(name, scene) {
  17603. if (scene === void 0) { scene = null; }
  17604. /**
  17605. * Gets or sets a string used to store user defined state for the node
  17606. */
  17607. this.state = "";
  17608. /**
  17609. * Gets or sets an object used to store user defined information for the node
  17610. */
  17611. this.metadata = null;
  17612. /**
  17613. * Gets or sets a boolean used to define if the node must be serialized
  17614. */
  17615. this.doNotSerialize = false;
  17616. /** @hidden */
  17617. this._isDisposed = false;
  17618. /**
  17619. * Gets a list of Animations associated with the node
  17620. */
  17621. this.animations = new Array();
  17622. this._ranges = {};
  17623. this._isEnabled = true;
  17624. this._isReady = true;
  17625. /** @hidden */
  17626. this._currentRenderId = -1;
  17627. this._parentRenderId = -1;
  17628. this._childRenderId = -1;
  17629. this._parentNode = null;
  17630. this._animationPropertiesOverride = null;
  17631. /**
  17632. * An event triggered when the mesh is disposed
  17633. */
  17634. this.onDisposeObservable = new BABYLON.Observable();
  17635. // Behaviors
  17636. this._behaviors = new Array();
  17637. this.name = name;
  17638. this.id = name;
  17639. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17640. this.uniqueId = this._scene.getUniqueId();
  17641. this._initCache();
  17642. }
  17643. /**
  17644. * Gets a boolean indicating if the node has been disposed
  17645. * @returns true if the node was disposed
  17646. */
  17647. Node.prototype.isDisposed = function () {
  17648. return this._isDisposed;
  17649. };
  17650. Object.defineProperty(Node.prototype, "parent", {
  17651. get: function () {
  17652. return this._parentNode;
  17653. },
  17654. /**
  17655. * Gets or sets the parent of the node
  17656. */
  17657. set: function (parent) {
  17658. if (this._parentNode === parent) {
  17659. return;
  17660. }
  17661. // Remove self from list of children of parent
  17662. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17663. var index = this._parentNode._children.indexOf(this);
  17664. if (index !== -1) {
  17665. this._parentNode._children.splice(index, 1);
  17666. }
  17667. }
  17668. // Store new parent
  17669. this._parentNode = parent;
  17670. // Add as child to new parent
  17671. if (this._parentNode) {
  17672. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17673. this._parentNode._children = new Array();
  17674. }
  17675. this._parentNode._children.push(this);
  17676. }
  17677. },
  17678. enumerable: true,
  17679. configurable: true
  17680. });
  17681. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17682. /**
  17683. * Gets or sets the animation properties override
  17684. */
  17685. get: function () {
  17686. if (!this._animationPropertiesOverride) {
  17687. return this._scene.animationPropertiesOverride;
  17688. }
  17689. return this._animationPropertiesOverride;
  17690. },
  17691. set: function (value) {
  17692. this._animationPropertiesOverride = value;
  17693. },
  17694. enumerable: true,
  17695. configurable: true
  17696. });
  17697. /**
  17698. * Gets a string idenfifying the name of the class
  17699. * @returns "Node" string
  17700. */
  17701. Node.prototype.getClassName = function () {
  17702. return "Node";
  17703. };
  17704. Object.defineProperty(Node.prototype, "onDispose", {
  17705. /**
  17706. * Sets a callback that will be raised when the node will be disposed
  17707. */
  17708. set: function (callback) {
  17709. if (this._onDisposeObserver) {
  17710. this.onDisposeObservable.remove(this._onDisposeObserver);
  17711. }
  17712. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17713. },
  17714. enumerable: true,
  17715. configurable: true
  17716. });
  17717. /**
  17718. * Gets the scene of the node
  17719. * @returns a {BABYLON.Scene}
  17720. */
  17721. Node.prototype.getScene = function () {
  17722. return this._scene;
  17723. };
  17724. /**
  17725. * Gets the engine of the node
  17726. * @returns a {BABYLON.Engine}
  17727. */
  17728. Node.prototype.getEngine = function () {
  17729. return this._scene.getEngine();
  17730. };
  17731. /**
  17732. * Attach a behavior to the node
  17733. * @see http://doc.babylonjs.com/features/behaviour
  17734. * @param behavior defines the behavior to attach
  17735. * @returns the current Node
  17736. */
  17737. Node.prototype.addBehavior = function (behavior) {
  17738. var _this = this;
  17739. var index = this._behaviors.indexOf(behavior);
  17740. if (index !== -1) {
  17741. return this;
  17742. }
  17743. behavior.init();
  17744. if (this._scene.isLoading) {
  17745. // We defer the attach when the scene will be loaded
  17746. this._scene.onDataLoadedObservable.addOnce(function () {
  17747. behavior.attach(_this);
  17748. });
  17749. }
  17750. else {
  17751. behavior.attach(this);
  17752. }
  17753. this._behaviors.push(behavior);
  17754. return this;
  17755. };
  17756. /**
  17757. * Remove an attached behavior
  17758. * @see http://doc.babylonjs.com/features/behaviour
  17759. * @param behavior defines the behavior to attach
  17760. * @returns the current Node
  17761. */
  17762. Node.prototype.removeBehavior = function (behavior) {
  17763. var index = this._behaviors.indexOf(behavior);
  17764. if (index === -1) {
  17765. return this;
  17766. }
  17767. this._behaviors[index].detach();
  17768. this._behaviors.splice(index, 1);
  17769. return this;
  17770. };
  17771. Object.defineProperty(Node.prototype, "behaviors", {
  17772. /**
  17773. * Gets the list of attached behaviors
  17774. * @see http://doc.babylonjs.com/features/behaviour
  17775. */
  17776. get: function () {
  17777. return this._behaviors;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. /**
  17783. * Gets an attached behavior by name
  17784. * @param name defines the name of the behavior to look for
  17785. * @see http://doc.babylonjs.com/features/behaviour
  17786. * @returns null if behavior was not found else the requested behavior
  17787. */
  17788. Node.prototype.getBehaviorByName = function (name) {
  17789. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17790. var behavior = _a[_i];
  17791. if (behavior.name === name) {
  17792. return behavior;
  17793. }
  17794. }
  17795. return null;
  17796. };
  17797. /**
  17798. * Returns the world matrix of the node
  17799. * @returns a matrix containing the node's world matrix
  17800. */
  17801. Node.prototype.getWorldMatrix = function () {
  17802. return BABYLON.Matrix.Identity();
  17803. };
  17804. /** @hidden */
  17805. Node.prototype._getWorldMatrixDeterminant = function () {
  17806. return 1;
  17807. };
  17808. // override it in derived class if you add new variables to the cache
  17809. // and call the parent class method
  17810. /** @hidden */
  17811. Node.prototype._initCache = function () {
  17812. this._cache = {};
  17813. this._cache.parent = undefined;
  17814. };
  17815. /** @hidden */
  17816. Node.prototype.updateCache = function (force) {
  17817. if (!force && this.isSynchronized())
  17818. return;
  17819. this._cache.parent = this.parent;
  17820. this._updateCache();
  17821. };
  17822. // override it in derived class if you add new variables to the cache
  17823. // and call the parent class method if !ignoreParentClass
  17824. /** @hidden */
  17825. Node.prototype._updateCache = function (ignoreParentClass) {
  17826. };
  17827. // override it in derived class if you add new variables to the cache
  17828. /** @hidden */
  17829. Node.prototype._isSynchronized = function () {
  17830. return true;
  17831. };
  17832. /** @hidden */
  17833. Node.prototype._markSyncedWithParent = function () {
  17834. if (this.parent) {
  17835. this._parentRenderId = this.parent._childRenderId;
  17836. }
  17837. };
  17838. /** @hidden */
  17839. Node.prototype.isSynchronizedWithParent = function () {
  17840. if (!this.parent) {
  17841. return true;
  17842. }
  17843. if (this._parentRenderId !== this.parent._childRenderId) {
  17844. return false;
  17845. }
  17846. return this.parent.isSynchronized();
  17847. };
  17848. /** @hidden */
  17849. Node.prototype.isSynchronized = function (updateCache) {
  17850. var check = this.hasNewParent();
  17851. check = check || !this.isSynchronizedWithParent();
  17852. check = check || !this._isSynchronized();
  17853. if (updateCache)
  17854. this.updateCache(true);
  17855. return !check;
  17856. };
  17857. /** @hidden */
  17858. Node.prototype.hasNewParent = function (update) {
  17859. if (this._cache.parent === this.parent)
  17860. return false;
  17861. if (update)
  17862. this._cache.parent = this.parent;
  17863. return true;
  17864. };
  17865. /**
  17866. * Is this node ready to be used/rendered
  17867. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17868. * @return true if the node is ready
  17869. */
  17870. Node.prototype.isReady = function (completeCheck) {
  17871. if (completeCheck === void 0) { completeCheck = false; }
  17872. return this._isReady;
  17873. };
  17874. /**
  17875. * Is this node enabled?
  17876. * 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
  17877. * @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
  17878. * @return whether this node (and its parent) is enabled
  17879. */
  17880. Node.prototype.isEnabled = function (checkAncestors) {
  17881. if (checkAncestors === void 0) { checkAncestors = true; }
  17882. if (checkAncestors === false) {
  17883. return this._isEnabled;
  17884. }
  17885. if (this._isEnabled === false) {
  17886. return false;
  17887. }
  17888. if (this.parent !== undefined && this.parent !== null) {
  17889. return this.parent.isEnabled(checkAncestors);
  17890. }
  17891. return true;
  17892. };
  17893. /**
  17894. * Set the enabled state of this node
  17895. * @param value defines the new enabled state
  17896. */
  17897. Node.prototype.setEnabled = function (value) {
  17898. this._isEnabled = value;
  17899. };
  17900. /**
  17901. * Is this node a descendant of the given node?
  17902. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17903. * @param ancestor defines the parent node to inspect
  17904. * @returns a boolean indicating if this node is a descendant of the given node
  17905. */
  17906. Node.prototype.isDescendantOf = function (ancestor) {
  17907. if (this.parent) {
  17908. if (this.parent === ancestor) {
  17909. return true;
  17910. }
  17911. return this.parent.isDescendantOf(ancestor);
  17912. }
  17913. return false;
  17914. };
  17915. /** @hidden */
  17916. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17917. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17918. if (!this._children) {
  17919. return;
  17920. }
  17921. for (var index = 0; index < this._children.length; index++) {
  17922. var item = this._children[index];
  17923. if (!predicate || predicate(item)) {
  17924. results.push(item);
  17925. }
  17926. if (!directDescendantsOnly) {
  17927. item._getDescendants(results, false, predicate);
  17928. }
  17929. }
  17930. };
  17931. /**
  17932. * Will return all nodes that have this node as ascendant
  17933. * @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
  17934. * @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
  17935. * @return all children nodes of all types
  17936. */
  17937. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17938. var results = new Array();
  17939. this._getDescendants(results, directDescendantsOnly, predicate);
  17940. return results;
  17941. };
  17942. /**
  17943. * Get all child-meshes of this node
  17944. * @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
  17945. * @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
  17946. * @returns an array of {BABYLON.AbstractMesh}
  17947. */
  17948. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17949. var results = [];
  17950. this._getDescendants(results, directDescendantsOnly, function (node) {
  17951. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17952. });
  17953. return results;
  17954. };
  17955. /**
  17956. * Get all child-transformNodes of this node
  17957. * @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
  17958. * @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
  17959. * @returns an array of {BABYLON.TransformNode}
  17960. */
  17961. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17962. var results = [];
  17963. this._getDescendants(results, directDescendantsOnly, function (node) {
  17964. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17965. });
  17966. return results;
  17967. };
  17968. /**
  17969. * Get all direct children of this node
  17970. * @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
  17971. * @returns an array of {BABYLON.Node}
  17972. */
  17973. Node.prototype.getChildren = function (predicate) {
  17974. return this.getDescendants(true, predicate);
  17975. };
  17976. /** @hidden */
  17977. Node.prototype._setReady = function (state) {
  17978. if (state === this._isReady) {
  17979. return;
  17980. }
  17981. if (!state) {
  17982. this._isReady = false;
  17983. return;
  17984. }
  17985. if (this.onReady) {
  17986. this.onReady(this);
  17987. }
  17988. this._isReady = true;
  17989. };
  17990. /**
  17991. * Get an animation by name
  17992. * @param name defines the name of the animation to look for
  17993. * @returns null if not found else the requested animation
  17994. */
  17995. Node.prototype.getAnimationByName = function (name) {
  17996. for (var i = 0; i < this.animations.length; i++) {
  17997. var animation = this.animations[i];
  17998. if (animation.name === name) {
  17999. return animation;
  18000. }
  18001. }
  18002. return null;
  18003. };
  18004. /**
  18005. * Creates an animation range for this node
  18006. * @param name defines the name of the range
  18007. * @param from defines the starting key
  18008. * @param to defines the end key
  18009. */
  18010. Node.prototype.createAnimationRange = function (name, from, to) {
  18011. // check name not already in use
  18012. if (!this._ranges[name]) {
  18013. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18014. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18015. if (this.animations[i]) {
  18016. this.animations[i].createRange(name, from, to);
  18017. }
  18018. }
  18019. }
  18020. };
  18021. /**
  18022. * Delete a specific animation range
  18023. * @param name defines the name of the range to delete
  18024. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18025. */
  18026. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18027. if (deleteFrames === void 0) { deleteFrames = true; }
  18028. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18029. if (this.animations[i]) {
  18030. this.animations[i].deleteRange(name, deleteFrames);
  18031. }
  18032. }
  18033. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18034. };
  18035. /**
  18036. * Get an animation range by name
  18037. * @param name defines the name of the animation range to look for
  18038. * @returns null if not found else the requested animation range
  18039. */
  18040. Node.prototype.getAnimationRange = function (name) {
  18041. return this._ranges[name];
  18042. };
  18043. /**
  18044. * Will start the animation sequence
  18045. * @param name defines the range frames for animation sequence
  18046. * @param loop defines if the animation should loop (false by default)
  18047. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18048. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18049. * @returns the object created for this animation. If range does not exist, it will return null
  18050. */
  18051. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18052. var range = this.getAnimationRange(name);
  18053. if (!range) {
  18054. return null;
  18055. }
  18056. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18057. };
  18058. /**
  18059. * Serialize animation ranges into a JSON compatible object
  18060. * @returns serialization object
  18061. */
  18062. Node.prototype.serializeAnimationRanges = function () {
  18063. var serializationRanges = [];
  18064. for (var name in this._ranges) {
  18065. var localRange = this._ranges[name];
  18066. if (!localRange) {
  18067. continue;
  18068. }
  18069. var range = {};
  18070. range.name = name;
  18071. range.from = localRange.from;
  18072. range.to = localRange.to;
  18073. serializationRanges.push(range);
  18074. }
  18075. return serializationRanges;
  18076. };
  18077. /**
  18078. * Computes the world matrix of the node
  18079. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18080. * @returns the world matrix
  18081. */
  18082. Node.prototype.computeWorldMatrix = function (force) {
  18083. return BABYLON.Matrix.Identity();
  18084. };
  18085. /**
  18086. * Releases resources associated with this node.
  18087. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18088. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18089. */
  18090. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18091. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18092. if (!doNotRecurse) {
  18093. var nodes = this.getDescendants(true);
  18094. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18095. var node = nodes_1[_i];
  18096. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18097. }
  18098. }
  18099. else {
  18100. var transformNodes = this.getChildTransformNodes(true);
  18101. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18102. var transformNode = transformNodes_1[_a];
  18103. transformNode.parent = null;
  18104. transformNode.computeWorldMatrix(true);
  18105. }
  18106. }
  18107. this.parent = null;
  18108. // Callback
  18109. this.onDisposeObservable.notifyObservers(this);
  18110. this.onDisposeObservable.clear();
  18111. // Behaviors
  18112. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18113. var behavior = _c[_b];
  18114. behavior.detach();
  18115. }
  18116. this._behaviors = [];
  18117. this._isDisposed = true;
  18118. };
  18119. /**
  18120. * Parse animation range data from a serialization object and store them into a given node
  18121. * @param node defines where to store the animation ranges
  18122. * @param parsedNode defines the serialization object to read data from
  18123. * @param scene defines the hosting scene
  18124. */
  18125. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18126. if (parsedNode.ranges) {
  18127. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18128. var data = parsedNode.ranges[index];
  18129. node.createAnimationRange(data.name, data.from, data.to);
  18130. }
  18131. }
  18132. };
  18133. __decorate([
  18134. BABYLON.serialize()
  18135. ], Node.prototype, "name", void 0);
  18136. __decorate([
  18137. BABYLON.serialize()
  18138. ], Node.prototype, "id", void 0);
  18139. __decorate([
  18140. BABYLON.serialize()
  18141. ], Node.prototype, "uniqueId", void 0);
  18142. __decorate([
  18143. BABYLON.serialize()
  18144. ], Node.prototype, "state", void 0);
  18145. __decorate([
  18146. BABYLON.serialize()
  18147. ], Node.prototype, "metadata", void 0);
  18148. return Node;
  18149. }());
  18150. BABYLON.Node = Node;
  18151. })(BABYLON || (BABYLON = {}));
  18152. //# sourceMappingURL=babylon.node.js.map
  18153. var BABYLON;
  18154. (function (BABYLON) {
  18155. var BoundingSphere = /** @class */ (function () {
  18156. /**
  18157. * Creates a new bounding sphere
  18158. * @param min defines the minimum vector (in local space)
  18159. * @param max defines the maximum vector (in local space)
  18160. */
  18161. function BoundingSphere(min, max) {
  18162. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18163. this.reConstruct(min, max);
  18164. }
  18165. /**
  18166. * Recreates the entire bounding sphere from scratch
  18167. * @param min defines the new minimum vector (in local space)
  18168. * @param max defines the new maximum vector (in local space)
  18169. */
  18170. BoundingSphere.prototype.reConstruct = function (min, max) {
  18171. this.minimum = min.clone();
  18172. this.maximum = max.clone();
  18173. var distance = BABYLON.Vector3.Distance(min, max);
  18174. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18175. this.radius = distance * 0.5;
  18176. this.centerWorld = BABYLON.Vector3.Zero();
  18177. this._update(BABYLON.Matrix.Identity());
  18178. };
  18179. // Methods
  18180. BoundingSphere.prototype._update = function (world) {
  18181. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18182. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18183. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18184. };
  18185. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18186. for (var i = 0; i < 6; i++) {
  18187. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18188. return false;
  18189. }
  18190. return true;
  18191. };
  18192. BoundingSphere.prototype.intersectsPoint = function (point) {
  18193. var x = this.centerWorld.x - point.x;
  18194. var y = this.centerWorld.y - point.y;
  18195. var z = this.centerWorld.z - point.z;
  18196. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18197. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18198. return false;
  18199. return true;
  18200. };
  18201. // Statics
  18202. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18203. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18204. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18205. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18206. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18207. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18208. return false;
  18209. return true;
  18210. };
  18211. return BoundingSphere;
  18212. }());
  18213. BABYLON.BoundingSphere = BoundingSphere;
  18214. })(BABYLON || (BABYLON = {}));
  18215. //# sourceMappingURL=babylon.boundingSphere.js.map
  18216. var BABYLON;
  18217. (function (BABYLON) {
  18218. var BoundingBox = /** @class */ (function () {
  18219. /**
  18220. * Creates a new bounding box
  18221. * @param min defines the minimum vector (in local space)
  18222. * @param max defines the maximum vector (in local space)
  18223. */
  18224. function BoundingBox(min, max) {
  18225. this.vectorsWorld = new Array();
  18226. this.reConstruct(min, max);
  18227. }
  18228. // Methods
  18229. /**
  18230. * Recreates the entire bounding box from scratch
  18231. * @param min defines the new minimum vector (in local space)
  18232. * @param max defines the new maximum vector (in local space)
  18233. */
  18234. BoundingBox.prototype.reConstruct = function (min, max) {
  18235. this.minimum = min.clone();
  18236. this.maximum = max.clone();
  18237. // Bounding vectors
  18238. this.vectors = new Array();
  18239. this.vectors.push(this.minimum.clone());
  18240. this.vectors.push(this.maximum.clone());
  18241. this.vectors.push(this.minimum.clone());
  18242. this.vectors[2].x = this.maximum.x;
  18243. this.vectors.push(this.minimum.clone());
  18244. this.vectors[3].y = this.maximum.y;
  18245. this.vectors.push(this.minimum.clone());
  18246. this.vectors[4].z = this.maximum.z;
  18247. this.vectors.push(this.maximum.clone());
  18248. this.vectors[5].z = this.minimum.z;
  18249. this.vectors.push(this.maximum.clone());
  18250. this.vectors[6].x = this.minimum.x;
  18251. this.vectors.push(this.maximum.clone());
  18252. this.vectors[7].y = this.minimum.y;
  18253. // OBB
  18254. this.center = this.maximum.add(this.minimum).scale(0.5);
  18255. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18256. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18257. // World
  18258. for (var index = 0; index < this.vectors.length; index++) {
  18259. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18260. }
  18261. this.minimumWorld = BABYLON.Vector3.Zero();
  18262. this.maximumWorld = BABYLON.Vector3.Zero();
  18263. this.centerWorld = BABYLON.Vector3.Zero();
  18264. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18265. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18266. };
  18267. BoundingBox.prototype.getWorldMatrix = function () {
  18268. return this._worldMatrix;
  18269. };
  18270. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18271. this._worldMatrix.copyFrom(matrix);
  18272. return this;
  18273. };
  18274. BoundingBox.prototype._update = function (world) {
  18275. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18276. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18277. for (var index = 0; index < this.vectors.length; index++) {
  18278. var v = this.vectorsWorld[index];
  18279. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18280. if (v.x < this.minimumWorld.x)
  18281. this.minimumWorld.x = v.x;
  18282. if (v.y < this.minimumWorld.y)
  18283. this.minimumWorld.y = v.y;
  18284. if (v.z < this.minimumWorld.z)
  18285. this.minimumWorld.z = v.z;
  18286. if (v.x > this.maximumWorld.x)
  18287. this.maximumWorld.x = v.x;
  18288. if (v.y > this.maximumWorld.y)
  18289. this.maximumWorld.y = v.y;
  18290. if (v.z > this.maximumWorld.z)
  18291. this.maximumWorld.z = v.z;
  18292. }
  18293. // Extend
  18294. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18295. this.extendSizeWorld.scaleInPlace(0.5);
  18296. // OBB
  18297. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18298. this.centerWorld.scaleInPlace(0.5);
  18299. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18300. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18301. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18302. this._worldMatrix = world;
  18303. };
  18304. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18305. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18306. };
  18307. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18308. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18309. };
  18310. BoundingBox.prototype.intersectsPoint = function (point) {
  18311. var delta = -BABYLON.Epsilon;
  18312. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18313. return false;
  18314. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18315. return false;
  18316. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18317. return false;
  18318. return true;
  18319. };
  18320. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18321. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18322. };
  18323. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18324. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18325. return false;
  18326. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18327. return false;
  18328. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18329. return false;
  18330. return true;
  18331. };
  18332. // Statics
  18333. BoundingBox.Intersects = function (box0, box1) {
  18334. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18335. return false;
  18336. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18337. return false;
  18338. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18339. return false;
  18340. return true;
  18341. };
  18342. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18343. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18344. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18345. return (num <= (sphereRadius * sphereRadius));
  18346. };
  18347. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18348. for (var p = 0; p < 6; p++) {
  18349. for (var i = 0; i < 8; i++) {
  18350. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18351. return false;
  18352. }
  18353. }
  18354. }
  18355. return true;
  18356. };
  18357. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18358. for (var p = 0; p < 6; p++) {
  18359. var inCount = 8;
  18360. for (var i = 0; i < 8; i++) {
  18361. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18362. --inCount;
  18363. }
  18364. else {
  18365. break;
  18366. }
  18367. }
  18368. if (inCount === 0)
  18369. return false;
  18370. }
  18371. return true;
  18372. };
  18373. return BoundingBox;
  18374. }());
  18375. BABYLON.BoundingBox = BoundingBox;
  18376. })(BABYLON || (BABYLON = {}));
  18377. //# sourceMappingURL=babylon.boundingBox.js.map
  18378. var BABYLON;
  18379. (function (BABYLON) {
  18380. var computeBoxExtents = function (axis, box) {
  18381. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18382. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18383. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18384. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18385. var r = r0 + r1 + r2;
  18386. return {
  18387. min: p - r,
  18388. max: p + r
  18389. };
  18390. };
  18391. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18392. var axisOverlap = function (axis, box0, box1) {
  18393. var result0 = computeBoxExtents(axis, box0);
  18394. var result1 = computeBoxExtents(axis, box1);
  18395. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18396. };
  18397. var BoundingInfo = /** @class */ (function () {
  18398. function BoundingInfo(minimum, maximum) {
  18399. this.minimum = minimum;
  18400. this.maximum = maximum;
  18401. this._isLocked = false;
  18402. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18403. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18404. }
  18405. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18406. get: function () {
  18407. return this._isLocked;
  18408. },
  18409. set: function (value) {
  18410. this._isLocked = value;
  18411. },
  18412. enumerable: true,
  18413. configurable: true
  18414. });
  18415. // Methods
  18416. BoundingInfo.prototype.update = function (world) {
  18417. if (this._isLocked) {
  18418. return;
  18419. }
  18420. this.boundingBox._update(world);
  18421. this.boundingSphere._update(world);
  18422. };
  18423. /**
  18424. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18425. * @param center New center of the bounding info
  18426. * @param extend New extend of the bounding info
  18427. */
  18428. BoundingInfo.prototype.centerOn = function (center, extend) {
  18429. this.minimum = center.subtract(extend);
  18430. this.maximum = center.add(extend);
  18431. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18432. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18433. return this;
  18434. };
  18435. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18436. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18437. return false;
  18438. return this.boundingBox.isInFrustum(frustumPlanes);
  18439. };
  18440. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18441. /**
  18442. * Gets the world distance between the min and max points of the bounding box
  18443. */
  18444. get: function () {
  18445. var boundingBox = this.boundingBox;
  18446. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18447. return size.length();
  18448. },
  18449. enumerable: true,
  18450. configurable: true
  18451. });
  18452. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18453. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18454. };
  18455. BoundingInfo.prototype._checkCollision = function (collider) {
  18456. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18457. };
  18458. BoundingInfo.prototype.intersectsPoint = function (point) {
  18459. if (!this.boundingSphere.centerWorld) {
  18460. return false;
  18461. }
  18462. if (!this.boundingSphere.intersectsPoint(point)) {
  18463. return false;
  18464. }
  18465. if (!this.boundingBox.intersectsPoint(point)) {
  18466. return false;
  18467. }
  18468. return true;
  18469. };
  18470. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18471. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18472. return false;
  18473. }
  18474. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18475. return false;
  18476. }
  18477. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18478. return false;
  18479. }
  18480. if (!precise) {
  18481. return true;
  18482. }
  18483. var box0 = this.boundingBox;
  18484. var box1 = boundingInfo.boundingBox;
  18485. if (!axisOverlap(box0.directions[0], box0, box1))
  18486. return false;
  18487. if (!axisOverlap(box0.directions[1], box0, box1))
  18488. return false;
  18489. if (!axisOverlap(box0.directions[2], box0, box1))
  18490. return false;
  18491. if (!axisOverlap(box1.directions[0], box0, box1))
  18492. return false;
  18493. if (!axisOverlap(box1.directions[1], box0, box1))
  18494. return false;
  18495. if (!axisOverlap(box1.directions[2], box0, box1))
  18496. return false;
  18497. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18498. return false;
  18499. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18500. return false;
  18501. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18502. return false;
  18503. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18504. return false;
  18505. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18506. return false;
  18507. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18508. return false;
  18509. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18510. return false;
  18511. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18512. return false;
  18513. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18514. return false;
  18515. return true;
  18516. };
  18517. return BoundingInfo;
  18518. }());
  18519. BABYLON.BoundingInfo = BoundingInfo;
  18520. })(BABYLON || (BABYLON = {}));
  18521. //# sourceMappingURL=babylon.boundingInfo.js.map
  18522. var BABYLON;
  18523. (function (BABYLON) {
  18524. var TransformNode = /** @class */ (function (_super) {
  18525. __extends(TransformNode, _super);
  18526. function TransformNode(name, scene, isPure) {
  18527. if (scene === void 0) { scene = null; }
  18528. if (isPure === void 0) { isPure = true; }
  18529. var _this = _super.call(this, name, scene) || this;
  18530. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18531. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18532. _this._up = new BABYLON.Vector3(0, 1, 0);
  18533. _this._right = new BABYLON.Vector3(1, 0, 0);
  18534. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18535. // Properties
  18536. _this._rotation = BABYLON.Vector3.Zero();
  18537. _this._scaling = BABYLON.Vector3.One();
  18538. _this._isDirty = false;
  18539. /**
  18540. * Set the billboard mode. Default is 0.
  18541. *
  18542. * | Value | Type | Description |
  18543. * | --- | --- | --- |
  18544. * | 0 | BILLBOARDMODE_NONE | |
  18545. * | 1 | BILLBOARDMODE_X | |
  18546. * | 2 | BILLBOARDMODE_Y | |
  18547. * | 4 | BILLBOARDMODE_Z | |
  18548. * | 7 | BILLBOARDMODE_ALL | |
  18549. *
  18550. */
  18551. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18552. _this.scalingDeterminant = 1;
  18553. _this.infiniteDistance = false;
  18554. /**
  18555. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18556. * By default the system will update normals to compensate
  18557. */
  18558. _this.ignoreNonUniformScaling = false;
  18559. _this.position = BABYLON.Vector3.Zero();
  18560. _this._localWorld = BABYLON.Matrix.Zero();
  18561. _this._worldMatrix = BABYLON.Matrix.Zero();
  18562. _this._worldMatrixDeterminant = 0;
  18563. _this._absolutePosition = BABYLON.Vector3.Zero();
  18564. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18565. _this._postMultiplyPivotMatrix = false;
  18566. _this._isWorldMatrixFrozen = false;
  18567. /**
  18568. * An event triggered after the world matrix is updated
  18569. */
  18570. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18571. _this._nonUniformScaling = false;
  18572. if (isPure) {
  18573. _this.getScene().addTransformNode(_this);
  18574. }
  18575. return _this;
  18576. }
  18577. /**
  18578. * Gets a string idenfifying the name of the class
  18579. * @returns "TransformNode" string
  18580. */
  18581. TransformNode.prototype.getClassName = function () {
  18582. return "TransformNode";
  18583. };
  18584. Object.defineProperty(TransformNode.prototype, "rotation", {
  18585. /**
  18586. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18587. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18588. * Default : (0.0, 0.0, 0.0)
  18589. */
  18590. get: function () {
  18591. return this._rotation;
  18592. },
  18593. set: function (newRotation) {
  18594. this._rotation = newRotation;
  18595. },
  18596. enumerable: true,
  18597. configurable: true
  18598. });
  18599. Object.defineProperty(TransformNode.prototype, "scaling", {
  18600. /**
  18601. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18602. * Default : (1.0, 1.0, 1.0)
  18603. */
  18604. get: function () {
  18605. return this._scaling;
  18606. },
  18607. /**
  18608. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18609. * Default : (1.0, 1.0, 1.0)
  18610. */
  18611. set: function (newScaling) {
  18612. this._scaling = newScaling;
  18613. },
  18614. enumerable: true,
  18615. configurable: true
  18616. });
  18617. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18618. /**
  18619. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18620. * It's null by default.
  18621. * 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)
  18622. */
  18623. get: function () {
  18624. return this._rotationQuaternion;
  18625. },
  18626. set: function (quaternion) {
  18627. this._rotationQuaternion = quaternion;
  18628. //reset the rotation vector.
  18629. if (quaternion && this.rotation.length()) {
  18630. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18631. }
  18632. },
  18633. enumerable: true,
  18634. configurable: true
  18635. });
  18636. Object.defineProperty(TransformNode.prototype, "forward", {
  18637. /**
  18638. * The forward direction of that transform in world space.
  18639. */
  18640. get: function () {
  18641. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18642. },
  18643. enumerable: true,
  18644. configurable: true
  18645. });
  18646. Object.defineProperty(TransformNode.prototype, "up", {
  18647. /**
  18648. * The up direction of that transform in world space.
  18649. */
  18650. get: function () {
  18651. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18652. },
  18653. enumerable: true,
  18654. configurable: true
  18655. });
  18656. Object.defineProperty(TransformNode.prototype, "right", {
  18657. /**
  18658. * The right direction of that transform in world space.
  18659. */
  18660. get: function () {
  18661. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18662. },
  18663. enumerable: true,
  18664. configurable: true
  18665. });
  18666. /**
  18667. * Returns the latest update of the World matrix
  18668. * Returns a Matrix.
  18669. */
  18670. TransformNode.prototype.getWorldMatrix = function () {
  18671. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18672. this.computeWorldMatrix();
  18673. }
  18674. return this._worldMatrix;
  18675. };
  18676. /** @hidden */
  18677. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18678. return this._worldMatrixDeterminant;
  18679. };
  18680. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18681. /**
  18682. * Returns directly the latest state of the mesh World matrix.
  18683. * A Matrix is returned.
  18684. */
  18685. get: function () {
  18686. return this._worldMatrix;
  18687. },
  18688. enumerable: true,
  18689. configurable: true
  18690. });
  18691. /**
  18692. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18693. * Returns the TransformNode.
  18694. */
  18695. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18696. this._poseMatrix.copyFrom(matrix);
  18697. return this;
  18698. };
  18699. /**
  18700. * Returns the mesh Pose matrix.
  18701. * Returned object : Matrix
  18702. */
  18703. TransformNode.prototype.getPoseMatrix = function () {
  18704. return this._poseMatrix;
  18705. };
  18706. TransformNode.prototype._isSynchronized = function () {
  18707. if (this._isDirty) {
  18708. return false;
  18709. }
  18710. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18711. return false;
  18712. if (this._cache.pivotMatrixUpdated) {
  18713. return false;
  18714. }
  18715. if (this.infiniteDistance) {
  18716. return false;
  18717. }
  18718. if (!this._cache.position.equals(this.position))
  18719. return false;
  18720. if (this.rotationQuaternion) {
  18721. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18722. return false;
  18723. }
  18724. if (!this._cache.rotation.equals(this.rotation))
  18725. return false;
  18726. if (!this._cache.scaling.equals(this.scaling))
  18727. return false;
  18728. return true;
  18729. };
  18730. TransformNode.prototype._initCache = function () {
  18731. _super.prototype._initCache.call(this);
  18732. this._cache.localMatrixUpdated = false;
  18733. this._cache.position = BABYLON.Vector3.Zero();
  18734. this._cache.scaling = BABYLON.Vector3.Zero();
  18735. this._cache.rotation = BABYLON.Vector3.Zero();
  18736. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18737. this._cache.billboardMode = -1;
  18738. };
  18739. TransformNode.prototype.markAsDirty = function (property) {
  18740. if (property === "rotation") {
  18741. this.rotationQuaternion = null;
  18742. }
  18743. this._currentRenderId = Number.MAX_VALUE;
  18744. this._isDirty = true;
  18745. return this;
  18746. };
  18747. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18748. /**
  18749. * Returns the current mesh absolute position.
  18750. * Retuns a Vector3.
  18751. */
  18752. get: function () {
  18753. return this._absolutePosition;
  18754. },
  18755. enumerable: true,
  18756. configurable: true
  18757. });
  18758. /**
  18759. * Sets a new matrix to apply before all other transformation
  18760. * @param matrix defines the transform matrix
  18761. * @returns the current TransformNode
  18762. */
  18763. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18764. return this.setPivotMatrix(matrix, false);
  18765. };
  18766. /**
  18767. * Sets a new pivot matrix to the current node
  18768. * @param matrix defines the new pivot matrix to use
  18769. * @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
  18770. * @returns the current TransformNode
  18771. */
  18772. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18773. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18774. this._pivotMatrix = matrix.clone();
  18775. this._cache.pivotMatrixUpdated = true;
  18776. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18777. if (this._postMultiplyPivotMatrix) {
  18778. if (!this._pivotMatrixInverse) {
  18779. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18780. }
  18781. else {
  18782. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18783. }
  18784. }
  18785. return this;
  18786. };
  18787. /**
  18788. * Returns the mesh pivot matrix.
  18789. * Default : Identity.
  18790. * A Matrix is returned.
  18791. */
  18792. TransformNode.prototype.getPivotMatrix = function () {
  18793. return this._pivotMatrix;
  18794. };
  18795. /**
  18796. * Prevents the World matrix to be computed any longer.
  18797. * Returns the TransformNode.
  18798. */
  18799. TransformNode.prototype.freezeWorldMatrix = function () {
  18800. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18801. this.computeWorldMatrix(true);
  18802. this._isWorldMatrixFrozen = true;
  18803. return this;
  18804. };
  18805. /**
  18806. * Allows back the World matrix computation.
  18807. * Returns the TransformNode.
  18808. */
  18809. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18810. this._isWorldMatrixFrozen = false;
  18811. this.computeWorldMatrix(true);
  18812. return this;
  18813. };
  18814. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18815. /**
  18816. * True if the World matrix has been frozen.
  18817. * Returns a boolean.
  18818. */
  18819. get: function () {
  18820. return this._isWorldMatrixFrozen;
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. /**
  18826. * Retuns the mesh absolute position in the World.
  18827. * Returns a Vector3.
  18828. */
  18829. TransformNode.prototype.getAbsolutePosition = function () {
  18830. this.computeWorldMatrix();
  18831. return this._absolutePosition;
  18832. };
  18833. /**
  18834. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18835. * Returns the TransformNode.
  18836. */
  18837. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18838. if (!absolutePosition) {
  18839. return this;
  18840. }
  18841. var absolutePositionX;
  18842. var absolutePositionY;
  18843. var absolutePositionZ;
  18844. if (absolutePosition.x === undefined) {
  18845. if (arguments.length < 3) {
  18846. return this;
  18847. }
  18848. absolutePositionX = arguments[0];
  18849. absolutePositionY = arguments[1];
  18850. absolutePositionZ = arguments[2];
  18851. }
  18852. else {
  18853. absolutePositionX = absolutePosition.x;
  18854. absolutePositionY = absolutePosition.y;
  18855. absolutePositionZ = absolutePosition.z;
  18856. }
  18857. if (this.parent) {
  18858. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18859. invertParentWorldMatrix.invert();
  18860. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18861. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18862. }
  18863. else {
  18864. this.position.x = absolutePositionX;
  18865. this.position.y = absolutePositionY;
  18866. this.position.z = absolutePositionZ;
  18867. }
  18868. return this;
  18869. };
  18870. /**
  18871. * Sets the mesh position in its local space.
  18872. * Returns the TransformNode.
  18873. */
  18874. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18875. this.computeWorldMatrix();
  18876. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18877. return this;
  18878. };
  18879. /**
  18880. * Returns the mesh position in the local space from the current World matrix values.
  18881. * Returns a new Vector3.
  18882. */
  18883. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18884. this.computeWorldMatrix();
  18885. var invLocalWorldMatrix = this._localWorld.clone();
  18886. invLocalWorldMatrix.invert();
  18887. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18888. };
  18889. /**
  18890. * Translates the mesh along the passed Vector3 in its local space.
  18891. * Returns the TransformNode.
  18892. */
  18893. TransformNode.prototype.locallyTranslate = function (vector3) {
  18894. this.computeWorldMatrix(true);
  18895. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18896. return this;
  18897. };
  18898. /**
  18899. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18900. * @param targetPoint the position (must be in same space as current mesh) to look at
  18901. * @param yawCor optional yaw (y-axis) correction in radians
  18902. * @param pitchCor optional pitch (x-axis) correction in radians
  18903. * @param rollCor optional roll (z-axis) correction in radians
  18904. * @param space the choosen space of the target
  18905. * @returns the TransformNode.
  18906. */
  18907. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18908. if (yawCor === void 0) { yawCor = 0; }
  18909. if (pitchCor === void 0) { pitchCor = 0; }
  18910. if (rollCor === void 0) { rollCor = 0; }
  18911. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18912. var dv = TransformNode._lookAtVectorCache;
  18913. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18914. targetPoint.subtractToRef(pos, dv);
  18915. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18916. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18917. var pitch = Math.atan2(dv.y, len);
  18918. if (this.rotationQuaternion) {
  18919. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18920. }
  18921. else {
  18922. this.rotation.x = pitch + pitchCor;
  18923. this.rotation.y = yaw + yawCor;
  18924. this.rotation.z = rollCor;
  18925. }
  18926. return this;
  18927. };
  18928. /**
  18929. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18930. * This Vector3 is expressed in the World space.
  18931. */
  18932. TransformNode.prototype.getDirection = function (localAxis) {
  18933. var result = BABYLON.Vector3.Zero();
  18934. this.getDirectionToRef(localAxis, result);
  18935. return result;
  18936. };
  18937. /**
  18938. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18939. * localAxis is expressed in the mesh local space.
  18940. * result is computed in the Wordl space from the mesh World matrix.
  18941. * Returns the TransformNode.
  18942. */
  18943. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18944. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18945. return this;
  18946. };
  18947. /**
  18948. * Sets a new pivot point to the current node
  18949. * @param point defines the new pivot point to use
  18950. * @param space defines if the point is in world or local space (local by default)
  18951. * @returns the current TransformNode
  18952. */
  18953. TransformNode.prototype.setPivotPoint = function (point, space) {
  18954. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18955. if (this.getScene().getRenderId() == 0) {
  18956. this.computeWorldMatrix(true);
  18957. }
  18958. var wm = this.getWorldMatrix();
  18959. if (space == BABYLON.Space.WORLD) {
  18960. var tmat = BABYLON.Tmp.Matrix[0];
  18961. wm.invertToRef(tmat);
  18962. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18963. }
  18964. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18965. };
  18966. /**
  18967. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18968. */
  18969. TransformNode.prototype.getPivotPoint = function () {
  18970. var point = BABYLON.Vector3.Zero();
  18971. this.getPivotPointToRef(point);
  18972. return point;
  18973. };
  18974. /**
  18975. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18976. * Returns the TransformNode.
  18977. */
  18978. TransformNode.prototype.getPivotPointToRef = function (result) {
  18979. result.x = -this._pivotMatrix.m[12];
  18980. result.y = -this._pivotMatrix.m[13];
  18981. result.z = -this._pivotMatrix.m[14];
  18982. return this;
  18983. };
  18984. /**
  18985. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18986. */
  18987. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18988. var point = BABYLON.Vector3.Zero();
  18989. this.getAbsolutePivotPointToRef(point);
  18990. return point;
  18991. };
  18992. /**
  18993. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18994. * Returns the TransformNode.
  18995. */
  18996. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18997. result.x = this._pivotMatrix.m[12];
  18998. result.y = this._pivotMatrix.m[13];
  18999. result.z = this._pivotMatrix.m[14];
  19000. this.getPivotPointToRef(result);
  19001. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19002. return this;
  19003. };
  19004. /**
  19005. * Defines the passed node as the parent of the current node.
  19006. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19007. * Returns the TransformNode.
  19008. */
  19009. TransformNode.prototype.setParent = function (node) {
  19010. if (node === null && this.parent === null) {
  19011. return this;
  19012. }
  19013. if (node === null) {
  19014. var rotation = BABYLON.Tmp.Quaternion[0];
  19015. var position = BABYLON.Tmp.Vector3[0];
  19016. var scale = BABYLON.Tmp.Vector3[1];
  19017. if (this.parent && this.parent.computeWorldMatrix) {
  19018. this.parent.computeWorldMatrix(true);
  19019. }
  19020. this.computeWorldMatrix(true);
  19021. this.getWorldMatrix().decompose(scale, rotation, position);
  19022. if (this.rotationQuaternion) {
  19023. this.rotationQuaternion.copyFrom(rotation);
  19024. }
  19025. else {
  19026. rotation.toEulerAnglesToRef(this.rotation);
  19027. }
  19028. this.scaling.x = scale.x;
  19029. this.scaling.y = scale.y;
  19030. this.scaling.z = scale.z;
  19031. this.position.x = position.x;
  19032. this.position.y = position.y;
  19033. this.position.z = position.z;
  19034. }
  19035. else {
  19036. var rotation = BABYLON.Tmp.Quaternion[0];
  19037. var position = BABYLON.Tmp.Vector3[0];
  19038. var scale = BABYLON.Tmp.Vector3[1];
  19039. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19040. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19041. this.computeWorldMatrix(true);
  19042. node.computeWorldMatrix(true);
  19043. node.getWorldMatrix().invertToRef(invParentMatrix);
  19044. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19045. diffMatrix.decompose(scale, rotation, position);
  19046. if (this.rotationQuaternion) {
  19047. this.rotationQuaternion.copyFrom(rotation);
  19048. }
  19049. else {
  19050. rotation.toEulerAnglesToRef(this.rotation);
  19051. }
  19052. this.position.x = position.x;
  19053. this.position.y = position.y;
  19054. this.position.z = position.z;
  19055. this.scaling.x = scale.x;
  19056. this.scaling.y = scale.y;
  19057. this.scaling.z = scale.z;
  19058. }
  19059. this.parent = node;
  19060. return this;
  19061. };
  19062. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19063. get: function () {
  19064. return this._nonUniformScaling;
  19065. },
  19066. enumerable: true,
  19067. configurable: true
  19068. });
  19069. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19070. if (this._nonUniformScaling === value) {
  19071. return false;
  19072. }
  19073. this._nonUniformScaling = value;
  19074. return true;
  19075. };
  19076. /**
  19077. * Attach the current TransformNode to another TransformNode associated with a bone
  19078. * @param bone Bone affecting the TransformNode
  19079. * @param affectedTransformNode TransformNode associated with the bone
  19080. */
  19081. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19082. this._transformToBoneReferal = affectedTransformNode;
  19083. this.parent = bone;
  19084. if (bone.getWorldMatrix().determinant() < 0) {
  19085. this.scalingDeterminant *= -1;
  19086. }
  19087. return this;
  19088. };
  19089. TransformNode.prototype.detachFromBone = function () {
  19090. if (!this.parent) {
  19091. return this;
  19092. }
  19093. if (this.parent.getWorldMatrix().determinant() < 0) {
  19094. this.scalingDeterminant *= -1;
  19095. }
  19096. this._transformToBoneReferal = null;
  19097. this.parent = null;
  19098. return this;
  19099. };
  19100. /**
  19101. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19102. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19103. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19104. * The passed axis is also normalized.
  19105. * Returns the TransformNode.
  19106. */
  19107. TransformNode.prototype.rotate = function (axis, amount, space) {
  19108. axis.normalize();
  19109. if (!this.rotationQuaternion) {
  19110. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19111. this.rotation = BABYLON.Vector3.Zero();
  19112. }
  19113. var rotationQuaternion;
  19114. if (!space || space === BABYLON.Space.LOCAL) {
  19115. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19116. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19117. }
  19118. else {
  19119. if (this.parent) {
  19120. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19121. invertParentWorldMatrix.invert();
  19122. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19123. }
  19124. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19125. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19126. }
  19127. return this;
  19128. };
  19129. /**
  19130. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19131. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19132. * The passed axis is also normalized.
  19133. * Returns the TransformNode.
  19134. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19135. */
  19136. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19137. axis.normalize();
  19138. if (!this.rotationQuaternion) {
  19139. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19140. this.rotation.copyFromFloats(0, 0, 0);
  19141. }
  19142. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19143. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19144. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19145. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19146. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19147. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19148. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19149. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19150. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19151. return this;
  19152. };
  19153. /**
  19154. * Translates the mesh along the axis vector for the passed distance in the given space.
  19155. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19156. * Returns the TransformNode.
  19157. */
  19158. TransformNode.prototype.translate = function (axis, distance, space) {
  19159. var displacementVector = axis.scale(distance);
  19160. if (!space || space === BABYLON.Space.LOCAL) {
  19161. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19162. this.setPositionWithLocalVector(tempV3);
  19163. }
  19164. else {
  19165. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19166. }
  19167. return this;
  19168. };
  19169. /**
  19170. * Adds a rotation step to the mesh current rotation.
  19171. * x, y, z are Euler angles expressed in radians.
  19172. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19173. * This means this rotation is made in the mesh local space only.
  19174. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19175. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19176. * ```javascript
  19177. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19178. * ```
  19179. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19180. * 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.
  19181. * Returns the TransformNode.
  19182. */
  19183. TransformNode.prototype.addRotation = function (x, y, z) {
  19184. var rotationQuaternion;
  19185. if (this.rotationQuaternion) {
  19186. rotationQuaternion = this.rotationQuaternion;
  19187. }
  19188. else {
  19189. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19190. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19191. }
  19192. var accumulation = BABYLON.Tmp.Quaternion[0];
  19193. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19194. rotationQuaternion.multiplyInPlace(accumulation);
  19195. if (!this.rotationQuaternion) {
  19196. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19197. }
  19198. return this;
  19199. };
  19200. /**
  19201. * Computes the mesh World matrix and returns it.
  19202. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19203. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19204. * If the parameter `force`is set to `true`, the actual computation is done.
  19205. * Returns the mesh World Matrix.
  19206. */
  19207. TransformNode.prototype.computeWorldMatrix = function (force) {
  19208. if (this._isWorldMatrixFrozen) {
  19209. return this._worldMatrix;
  19210. }
  19211. if (!force && this.isSynchronized(true)) {
  19212. this._currentRenderId = this.getScene().getRenderId();
  19213. return this._worldMatrix;
  19214. }
  19215. this._cache.position.copyFrom(this.position);
  19216. this._cache.scaling.copyFrom(this.scaling);
  19217. this._cache.pivotMatrixUpdated = false;
  19218. this._cache.billboardMode = this.billboardMode;
  19219. this._currentRenderId = this.getScene().getRenderId();
  19220. this._childRenderId = this.getScene().getRenderId();
  19221. this._isDirty = false;
  19222. // Scaling
  19223. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19224. // Rotation
  19225. //rotate, if quaternion is set and rotation was used
  19226. if (this.rotationQuaternion) {
  19227. var len = this.rotation.length();
  19228. if (len) {
  19229. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19230. this.rotation.copyFromFloats(0, 0, 0);
  19231. }
  19232. }
  19233. if (this.rotationQuaternion) {
  19234. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19235. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19236. }
  19237. else {
  19238. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19239. this._cache.rotation.copyFrom(this.rotation);
  19240. }
  19241. // Translation
  19242. var camera = this.getScene().activeCamera;
  19243. if (this.infiniteDistance && !this.parent && camera) {
  19244. var cameraWorldMatrix = camera.getWorldMatrix();
  19245. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19246. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19247. }
  19248. else {
  19249. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19250. }
  19251. // Composing transformations
  19252. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19253. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19254. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19255. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19256. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19257. // Need to decompose each rotation here
  19258. var currentPosition = BABYLON.Tmp.Vector3[3];
  19259. if (this.parent && this.parent.getWorldMatrix) {
  19260. if (this._transformToBoneReferal) {
  19261. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19262. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19263. }
  19264. else {
  19265. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19266. }
  19267. }
  19268. else {
  19269. currentPosition.copyFrom(this.position);
  19270. }
  19271. currentPosition.subtractInPlace(camera.globalPosition);
  19272. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19273. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19274. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19275. }
  19276. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19277. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19278. }
  19279. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19280. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19281. }
  19282. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19283. }
  19284. else {
  19285. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19286. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19287. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19288. }
  19289. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19290. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19291. }
  19292. // Local world
  19293. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19294. // Parent
  19295. if (this.parent && this.parent.getWorldMatrix) {
  19296. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19297. if (this._transformToBoneReferal) {
  19298. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19299. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19300. }
  19301. else {
  19302. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19303. }
  19304. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19305. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19306. this._worldMatrix.copyFrom(this._localWorld);
  19307. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19308. }
  19309. else {
  19310. if (this._transformToBoneReferal) {
  19311. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19312. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19313. }
  19314. else {
  19315. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19316. }
  19317. }
  19318. this._markSyncedWithParent();
  19319. }
  19320. else {
  19321. this._worldMatrix.copyFrom(this._localWorld);
  19322. }
  19323. // Post multiply inverse of pivotMatrix
  19324. if (this._postMultiplyPivotMatrix) {
  19325. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19326. }
  19327. // Normal matrix
  19328. if (!this.ignoreNonUniformScaling) {
  19329. if (this.scaling.isNonUniform) {
  19330. this._updateNonUniformScalingState(true);
  19331. }
  19332. else if (this.parent && this.parent._nonUniformScaling) {
  19333. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19334. }
  19335. else {
  19336. this._updateNonUniformScalingState(false);
  19337. }
  19338. }
  19339. else {
  19340. this._updateNonUniformScalingState(false);
  19341. }
  19342. this._afterComputeWorldMatrix();
  19343. // Absolute position
  19344. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19345. // Callbacks
  19346. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19347. if (!this._poseMatrix) {
  19348. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19349. }
  19350. // Cache the determinant
  19351. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19352. return this._worldMatrix;
  19353. };
  19354. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19355. };
  19356. /**
  19357. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19358. * @param func: callback function to add
  19359. *
  19360. * Returns the TransformNode.
  19361. */
  19362. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19363. this.onAfterWorldMatrixUpdateObservable.add(func);
  19364. return this;
  19365. };
  19366. /**
  19367. * Removes a registered callback function.
  19368. * Returns the TransformNode.
  19369. */
  19370. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19371. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19372. return this;
  19373. };
  19374. /**
  19375. * Clone the current transform node
  19376. * Returns the new transform node
  19377. * @param name Name of the new clone
  19378. * @param newParent New parent for the clone
  19379. * @param doNotCloneChildren Do not clone children hierarchy
  19380. */
  19381. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19382. var _this = this;
  19383. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19384. result.name = name;
  19385. result.id = name;
  19386. if (newParent) {
  19387. result.parent = newParent;
  19388. }
  19389. if (!doNotCloneChildren) {
  19390. // Children
  19391. var directDescendants = this.getDescendants(true);
  19392. for (var index = 0; index < directDescendants.length; index++) {
  19393. var child = directDescendants[index];
  19394. if (child.clone) {
  19395. child.clone(name + "." + child.name, result);
  19396. }
  19397. }
  19398. }
  19399. return result;
  19400. };
  19401. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19402. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19403. serializationObject.type = this.getClassName();
  19404. // Parent
  19405. if (this.parent) {
  19406. serializationObject.parentId = this.parent.id;
  19407. }
  19408. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19409. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19410. }
  19411. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19412. serializationObject.isEnabled = this.isEnabled();
  19413. // Parent
  19414. if (this.parent) {
  19415. serializationObject.parentId = this.parent.id;
  19416. }
  19417. return serializationObject;
  19418. };
  19419. // Statics
  19420. /**
  19421. * Returns a new TransformNode object parsed from the source provided.
  19422. * The parameter `parsedMesh` is the source.
  19423. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19424. */
  19425. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19426. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19427. if (BABYLON.Tags) {
  19428. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19429. }
  19430. if (parsedTransformNode.localMatrix) {
  19431. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19432. }
  19433. else if (parsedTransformNode.pivotMatrix) {
  19434. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19435. }
  19436. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19437. // Parent
  19438. if (parsedTransformNode.parentId) {
  19439. transformNode._waitingParentId = parsedTransformNode.parentId;
  19440. }
  19441. return transformNode;
  19442. };
  19443. /**
  19444. * Releases resources associated with this transform node.
  19445. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19446. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19447. */
  19448. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19450. // Animations
  19451. this.getScene().stopAnimation(this);
  19452. // Remove from scene
  19453. this.getScene().removeTransformNode(this);
  19454. this.onAfterWorldMatrixUpdateObservable.clear();
  19455. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19456. };
  19457. // Statics
  19458. TransformNode.BILLBOARDMODE_NONE = 0;
  19459. TransformNode.BILLBOARDMODE_X = 1;
  19460. TransformNode.BILLBOARDMODE_Y = 2;
  19461. TransformNode.BILLBOARDMODE_Z = 4;
  19462. TransformNode.BILLBOARDMODE_ALL = 7;
  19463. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19464. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19465. __decorate([
  19466. BABYLON.serializeAsVector3()
  19467. ], TransformNode.prototype, "_rotation", void 0);
  19468. __decorate([
  19469. BABYLON.serializeAsQuaternion()
  19470. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19471. __decorate([
  19472. BABYLON.serializeAsVector3()
  19473. ], TransformNode.prototype, "_scaling", void 0);
  19474. __decorate([
  19475. BABYLON.serialize()
  19476. ], TransformNode.prototype, "billboardMode", void 0);
  19477. __decorate([
  19478. BABYLON.serialize()
  19479. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19480. __decorate([
  19481. BABYLON.serialize()
  19482. ], TransformNode.prototype, "infiniteDistance", void 0);
  19483. __decorate([
  19484. BABYLON.serialize()
  19485. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19486. __decorate([
  19487. BABYLON.serializeAsVector3()
  19488. ], TransformNode.prototype, "position", void 0);
  19489. return TransformNode;
  19490. }(BABYLON.Node));
  19491. BABYLON.TransformNode = TransformNode;
  19492. })(BABYLON || (BABYLON = {}));
  19493. //# sourceMappingURL=babylon.transformNode.js.map
  19494. var BABYLON;
  19495. (function (BABYLON) {
  19496. /**
  19497. * Class used to store all common mesh properties
  19498. */
  19499. var AbstractMesh = /** @class */ (function (_super) {
  19500. __extends(AbstractMesh, _super);
  19501. // Constructor
  19502. /**
  19503. * Creates a new AbstractMesh
  19504. * @param name defines the name of the mesh
  19505. * @param scene defines the hosting scene
  19506. */
  19507. function AbstractMesh(name, scene) {
  19508. if (scene === void 0) { scene = null; }
  19509. var _this = _super.call(this, name, scene, false) || this;
  19510. _this._facetNb = 0; // facet number
  19511. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19512. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19513. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19514. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19515. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19516. _this._subDiv = {
  19517. max: 1,
  19518. X: 1,
  19519. Y: 1,
  19520. Z: 1
  19521. };
  19522. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19523. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19524. // Events
  19525. /**
  19526. * An event triggered when this mesh collides with another one
  19527. */
  19528. _this.onCollideObservable = new BABYLON.Observable();
  19529. /**
  19530. * An event triggered when the collision's position changes
  19531. */
  19532. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19533. /**
  19534. * An event triggered when material is changed
  19535. */
  19536. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19537. // Properties
  19538. /**
  19539. * Gets or sets the orientation for POV movement & rotation
  19540. */
  19541. _this.definedFacingForward = true;
  19542. /**
  19543. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19544. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19545. * * 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.
  19546. * @see http://doc.babylonjs.com/features/occlusionquery
  19547. */
  19548. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19549. /**
  19550. * 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:
  19551. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19552. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19553. * * 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.
  19554. * @see http://doc.babylonjs.com/features/occlusionquery
  19555. */
  19556. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19557. /**
  19558. * 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.
  19559. * The default value is -1 which means don't break the query and wait till the result
  19560. * @see http://doc.babylonjs.com/features/occlusionquery
  19561. */
  19562. _this.occlusionRetryCount = -1;
  19563. _this._occlusionInternalRetryCounter = 0;
  19564. _this._isOccluded = false;
  19565. _this._isOcclusionQueryInProgress = false;
  19566. _this._visibility = 1.0;
  19567. /** Gets or sets the alpha index used to sort transparent meshes
  19568. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19569. */
  19570. _this.alphaIndex = Number.MAX_VALUE;
  19571. /**
  19572. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19573. */
  19574. _this.isVisible = true;
  19575. /**
  19576. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19577. */
  19578. _this.isPickable = true;
  19579. /**
  19580. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19581. */
  19582. _this.showBoundingBox = false;
  19583. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19584. _this.showSubMeshesBoundingBox = false;
  19585. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19586. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19587. */
  19588. _this.isBlocker = false;
  19589. /**
  19590. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19591. */
  19592. _this.enablePointerMoveEvents = false;
  19593. /**
  19594. * Specifies the rendering group id for this mesh (0 by default)
  19595. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19596. */
  19597. _this.renderingGroupId = 0;
  19598. _this._receiveShadows = false;
  19599. /**
  19600. * Gets or sets a boolean indicating if the outline must be rendered as well
  19601. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19602. */
  19603. _this.renderOutline = false;
  19604. /** Defines color to use when rendering outline */
  19605. _this.outlineColor = BABYLON.Color3.Red();
  19606. /** Define width to use when rendering outline */
  19607. _this.outlineWidth = 0.02;
  19608. /**
  19609. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19610. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19611. */
  19612. _this.renderOverlay = false;
  19613. /** Defines color to use when rendering overlay */
  19614. _this.overlayColor = BABYLON.Color3.Red();
  19615. /** Defines alpha to use when rendering overlay */
  19616. _this.overlayAlpha = 0.5;
  19617. _this._hasVertexAlpha = false;
  19618. _this._useVertexColors = true;
  19619. _this._computeBonesUsingShaders = true;
  19620. _this._numBoneInfluencers = 4;
  19621. _this._applyFog = true;
  19622. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19623. _this.useOctreeForRenderingSelection = true;
  19624. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19625. _this.useOctreeForPicking = true;
  19626. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19627. _this.useOctreeForCollisions = true;
  19628. _this._layerMask = 0x0FFFFFFF;
  19629. /**
  19630. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19631. */
  19632. _this.alwaysSelectAsActiveMesh = false;
  19633. /**
  19634. * Gets or sets the current action manager
  19635. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19636. */
  19637. _this.actionManager = null;
  19638. /**
  19639. * Gets or sets impostor used for physic simulation
  19640. * @see http://doc.babylonjs.com/features/physics_engine
  19641. */
  19642. _this.physicsImpostor = null;
  19643. // Collisions
  19644. _this._checkCollisions = false;
  19645. _this._collisionMask = -1;
  19646. _this._collisionGroup = -1;
  19647. /**
  19648. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19649. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19650. */
  19651. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19652. /**
  19653. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19654. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19655. */
  19656. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19657. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19658. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19659. // Edges
  19660. /**
  19661. * Defines edge width used when edgesRenderer is enabled
  19662. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19663. */
  19664. _this.edgesWidth = 1;
  19665. /**
  19666. * Defines edge color used when edgesRenderer is enabled
  19667. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19668. */
  19669. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19670. // Cache
  19671. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19672. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19673. /** @hidden */
  19674. _this._renderId = 0;
  19675. /** @hidden */
  19676. _this._intersectionsInProgress = new Array();
  19677. /** @hidden */
  19678. _this._unIndexed = false;
  19679. /** @hidden */
  19680. _this._lightSources = new Array();
  19681. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19682. if (collidedMesh === void 0) { collidedMesh = null; }
  19683. //TODO move this to the collision coordinator!
  19684. if (_this.getScene().workerCollisions)
  19685. newPosition.multiplyInPlace(_this._collider._radius);
  19686. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19687. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19688. _this.position.addInPlace(_this._diffPositionForCollisions);
  19689. }
  19690. if (collidedMesh) {
  19691. _this.onCollideObservable.notifyObservers(collidedMesh);
  19692. }
  19693. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19694. };
  19695. _this.getScene().addMesh(_this);
  19696. _this._resyncLightSources();
  19697. return _this;
  19698. }
  19699. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19700. /**
  19701. * No billboard
  19702. */
  19703. get: function () {
  19704. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19705. },
  19706. enumerable: true,
  19707. configurable: true
  19708. });
  19709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19710. /** Billboard on X axis */
  19711. get: function () {
  19712. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19713. },
  19714. enumerable: true,
  19715. configurable: true
  19716. });
  19717. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19718. /** Billboard on Y axis */
  19719. get: function () {
  19720. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19721. },
  19722. enumerable: true,
  19723. configurable: true
  19724. });
  19725. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19726. /** Billboard on Z axis */
  19727. get: function () {
  19728. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19734. /** Billboard on all axes */
  19735. get: function () {
  19736. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19737. },
  19738. enumerable: true,
  19739. configurable: true
  19740. });
  19741. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19742. /**
  19743. * Gets the number of facets in the mesh
  19744. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19745. */
  19746. get: function () {
  19747. return this._facetNb;
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19753. /**
  19754. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19755. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19756. */
  19757. get: function () {
  19758. return this._partitioningSubdivisions;
  19759. },
  19760. set: function (nb) {
  19761. this._partitioningSubdivisions = nb;
  19762. },
  19763. enumerable: true,
  19764. configurable: true
  19765. });
  19766. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19767. /**
  19768. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19769. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19770. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19771. */
  19772. get: function () {
  19773. return this._partitioningBBoxRatio;
  19774. },
  19775. set: function (ratio) {
  19776. this._partitioningBBoxRatio = ratio;
  19777. },
  19778. enumerable: true,
  19779. configurable: true
  19780. });
  19781. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19782. /**
  19783. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19784. * Works only for updatable meshes.
  19785. * Doesn't work with multi-materials
  19786. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19787. */
  19788. get: function () {
  19789. return this._facetDepthSort;
  19790. },
  19791. set: function (sort) {
  19792. this._facetDepthSort = sort;
  19793. },
  19794. enumerable: true,
  19795. configurable: true
  19796. });
  19797. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19798. /**
  19799. * The location (Vector3) where the facet depth sort must be computed from.
  19800. * By default, the active camera position.
  19801. * Used only when facet depth sort is enabled
  19802. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19803. */
  19804. get: function () {
  19805. return this._facetDepthSortFrom;
  19806. },
  19807. set: function (location) {
  19808. this._facetDepthSortFrom = location;
  19809. },
  19810. enumerable: true,
  19811. configurable: true
  19812. });
  19813. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19814. /**
  19815. * gets a boolean indicating if facetData is enabled
  19816. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19817. */
  19818. get: function () {
  19819. return this._facetDataEnabled;
  19820. },
  19821. enumerable: true,
  19822. configurable: true
  19823. });
  19824. /** @hidden */
  19825. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19826. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19827. return false;
  19828. }
  19829. this._markSubMeshesAsMiscDirty();
  19830. return true;
  19831. };
  19832. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19833. /** Set a function to call when this mesh collides with another one */
  19834. set: function (callback) {
  19835. if (this._onCollideObserver) {
  19836. this.onCollideObservable.remove(this._onCollideObserver);
  19837. }
  19838. this._onCollideObserver = this.onCollideObservable.add(callback);
  19839. },
  19840. enumerable: true,
  19841. configurable: true
  19842. });
  19843. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19844. /** Set a function to call when the collision's position changes */
  19845. set: function (callback) {
  19846. if (this._onCollisionPositionChangeObserver) {
  19847. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19848. }
  19849. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19855. /**
  19856. * 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
  19857. * @see http://doc.babylonjs.com/features/occlusionquery
  19858. */
  19859. get: function () {
  19860. return this._isOccluded;
  19861. },
  19862. set: function (value) {
  19863. this._isOccluded = value;
  19864. },
  19865. enumerable: true,
  19866. configurable: true
  19867. });
  19868. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19869. /**
  19870. * Flag to check the progress status of the query
  19871. * @see http://doc.babylonjs.com/features/occlusionquery
  19872. */
  19873. get: function () {
  19874. return this._isOcclusionQueryInProgress;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19880. /**
  19881. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19882. */
  19883. get: function () {
  19884. return this._visibility;
  19885. },
  19886. /**
  19887. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19888. */
  19889. set: function (value) {
  19890. if (this._visibility === value) {
  19891. return;
  19892. }
  19893. this._visibility = value;
  19894. this._markSubMeshesAsMiscDirty();
  19895. },
  19896. enumerable: true,
  19897. configurable: true
  19898. });
  19899. Object.defineProperty(AbstractMesh.prototype, "material", {
  19900. /** Gets or sets current material */
  19901. get: function () {
  19902. return this._material;
  19903. },
  19904. set: function (value) {
  19905. if (this._material === value) {
  19906. return;
  19907. }
  19908. this._material = value;
  19909. if (this.onMaterialChangedObservable.hasObservers) {
  19910. this.onMaterialChangedObservable.notifyObservers(this);
  19911. }
  19912. if (!this.subMeshes) {
  19913. return;
  19914. }
  19915. this._unBindEffect();
  19916. },
  19917. enumerable: true,
  19918. configurable: true
  19919. });
  19920. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19921. /**
  19922. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19923. * @see http://doc.babylonjs.com/babylon101/shadows
  19924. */
  19925. get: function () {
  19926. return this._receiveShadows;
  19927. },
  19928. set: function (value) {
  19929. if (this._receiveShadows === value) {
  19930. return;
  19931. }
  19932. this._receiveShadows = value;
  19933. this._markSubMeshesAsLightDirty();
  19934. },
  19935. enumerable: true,
  19936. configurable: true
  19937. });
  19938. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19939. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19940. get: function () {
  19941. return this._hasVertexAlpha;
  19942. },
  19943. set: function (value) {
  19944. if (this._hasVertexAlpha === value) {
  19945. return;
  19946. }
  19947. this._hasVertexAlpha = value;
  19948. this._markSubMeshesAsAttributesDirty();
  19949. this._markSubMeshesAsMiscDirty();
  19950. },
  19951. enumerable: true,
  19952. configurable: true
  19953. });
  19954. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19955. /** 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) */
  19956. get: function () {
  19957. return this._useVertexColors;
  19958. },
  19959. set: function (value) {
  19960. if (this._useVertexColors === value) {
  19961. return;
  19962. }
  19963. this._useVertexColors = value;
  19964. this._markSubMeshesAsAttributesDirty();
  19965. },
  19966. enumerable: true,
  19967. configurable: true
  19968. });
  19969. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19970. /**
  19971. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19972. */
  19973. get: function () {
  19974. return this._computeBonesUsingShaders;
  19975. },
  19976. set: function (value) {
  19977. if (this._computeBonesUsingShaders === value) {
  19978. return;
  19979. }
  19980. this._computeBonesUsingShaders = value;
  19981. this._markSubMeshesAsAttributesDirty();
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19987. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19988. get: function () {
  19989. return this._numBoneInfluencers;
  19990. },
  19991. set: function (value) {
  19992. if (this._numBoneInfluencers === value) {
  19993. return;
  19994. }
  19995. this._numBoneInfluencers = value;
  19996. this._markSubMeshesAsAttributesDirty();
  19997. },
  19998. enumerable: true,
  19999. configurable: true
  20000. });
  20001. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20002. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20003. get: function () {
  20004. return this._applyFog;
  20005. },
  20006. set: function (value) {
  20007. if (this._applyFog === value) {
  20008. return;
  20009. }
  20010. this._applyFog = value;
  20011. this._markSubMeshesAsMiscDirty();
  20012. },
  20013. enumerable: true,
  20014. configurable: true
  20015. });
  20016. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20017. /**
  20018. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20019. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20020. */
  20021. get: function () {
  20022. return this._layerMask;
  20023. },
  20024. set: function (value) {
  20025. if (value === this._layerMask) {
  20026. return;
  20027. }
  20028. this._layerMask = value;
  20029. this._resyncLightSources();
  20030. },
  20031. enumerable: true,
  20032. configurable: true
  20033. });
  20034. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20035. /**
  20036. * Gets or sets a collision mask used to mask collisions (default is -1).
  20037. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20038. */
  20039. get: function () {
  20040. return this._collisionMask;
  20041. },
  20042. set: function (mask) {
  20043. this._collisionMask = !isNaN(mask) ? mask : -1;
  20044. },
  20045. enumerable: true,
  20046. configurable: true
  20047. });
  20048. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20049. /**
  20050. * Gets or sets the current collision group mask (-1 by default).
  20051. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20052. */
  20053. get: function () {
  20054. return this._collisionGroup;
  20055. },
  20056. set: function (mask) {
  20057. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20058. },
  20059. enumerable: true,
  20060. configurable: true
  20061. });
  20062. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20063. /** @hidden */
  20064. get: function () {
  20065. return null;
  20066. },
  20067. enumerable: true,
  20068. configurable: true
  20069. });
  20070. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20071. get: function () {
  20072. return this._skeleton;
  20073. },
  20074. /**
  20075. * Gets or sets a skeleton to apply skining transformations
  20076. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20077. */
  20078. set: function (value) {
  20079. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20080. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20081. }
  20082. if (value && value.needInitialSkinMatrix) {
  20083. value._registerMeshWithPoseMatrix(this);
  20084. }
  20085. this._skeleton = value;
  20086. if (!this._skeleton) {
  20087. this._bonesTransformMatrices = null;
  20088. }
  20089. this._markSubMeshesAsAttributesDirty();
  20090. },
  20091. enumerable: true,
  20092. configurable: true
  20093. });
  20094. /**
  20095. * Returns the string "AbstractMesh"
  20096. * @returns "AbstractMesh"
  20097. */
  20098. AbstractMesh.prototype.getClassName = function () {
  20099. return "AbstractMesh";
  20100. };
  20101. /**
  20102. * Gets a string representation of the current mesh
  20103. * @param fullDetails defines a boolean indicating if full details must be included
  20104. * @returns a string representation of the current mesh
  20105. */
  20106. AbstractMesh.prototype.toString = function (fullDetails) {
  20107. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20108. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20109. if (this._skeleton) {
  20110. ret += ", skeleton: " + this._skeleton.name;
  20111. }
  20112. if (fullDetails) {
  20113. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20114. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20115. }
  20116. return ret;
  20117. };
  20118. /** @hidden */
  20119. AbstractMesh.prototype._rebuild = function () {
  20120. if (this._occlusionQuery) {
  20121. this._occlusionQuery = null;
  20122. }
  20123. if (this._edgesRenderer) {
  20124. this._edgesRenderer._rebuild();
  20125. }
  20126. if (!this.subMeshes) {
  20127. return;
  20128. }
  20129. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20130. var subMesh = _a[_i];
  20131. subMesh._rebuild();
  20132. }
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._resyncLightSources = function () {
  20136. this._lightSources.length = 0;
  20137. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20138. var light = _a[_i];
  20139. if (!light.isEnabled()) {
  20140. continue;
  20141. }
  20142. if (light.canAffectMesh(this)) {
  20143. this._lightSources.push(light);
  20144. }
  20145. }
  20146. this._markSubMeshesAsLightDirty();
  20147. };
  20148. /** @hidden */
  20149. AbstractMesh.prototype._resyncLighSource = function (light) {
  20150. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20151. var index = this._lightSources.indexOf(light);
  20152. if (index === -1) {
  20153. if (!isIn) {
  20154. return;
  20155. }
  20156. this._lightSources.push(light);
  20157. }
  20158. else {
  20159. if (isIn) {
  20160. return;
  20161. }
  20162. this._lightSources.splice(index, 1);
  20163. }
  20164. this._markSubMeshesAsLightDirty();
  20165. };
  20166. /** @hidden */
  20167. AbstractMesh.prototype._unBindEffect = function () {
  20168. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20169. var subMesh = _a[_i];
  20170. subMesh.setEffect(null);
  20171. }
  20172. };
  20173. /** @hidden */
  20174. AbstractMesh.prototype._removeLightSource = function (light) {
  20175. var index = this._lightSources.indexOf(light);
  20176. if (index === -1) {
  20177. return;
  20178. }
  20179. this._lightSources.splice(index, 1);
  20180. this._markSubMeshesAsLightDirty();
  20181. };
  20182. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20183. if (!this.subMeshes) {
  20184. return;
  20185. }
  20186. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20187. var subMesh = _a[_i];
  20188. if (subMesh._materialDefines) {
  20189. func(subMesh._materialDefines);
  20190. }
  20191. }
  20192. };
  20193. /** @hidden */
  20194. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20195. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20196. };
  20197. /** @hidden */
  20198. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20199. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20200. };
  20201. /** @hidden */
  20202. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20203. if (!this.subMeshes) {
  20204. return;
  20205. }
  20206. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20207. var subMesh = _a[_i];
  20208. var material = subMesh.getMaterial();
  20209. if (material) {
  20210. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20211. }
  20212. }
  20213. };
  20214. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20215. /**
  20216. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20217. */
  20218. get: function () {
  20219. return this._scaling;
  20220. },
  20221. set: function (newScaling) {
  20222. this._scaling = newScaling;
  20223. if (this.physicsImpostor) {
  20224. this.physicsImpostor.forceUpdate();
  20225. }
  20226. },
  20227. enumerable: true,
  20228. configurable: true
  20229. });
  20230. // Methods
  20231. /**
  20232. * Disables the mesh edge rendering mode
  20233. * @returns the currentAbstractMesh
  20234. */
  20235. AbstractMesh.prototype.disableEdgesRendering = function () {
  20236. if (this._edgesRenderer) {
  20237. this._edgesRenderer.dispose();
  20238. this._edgesRenderer = null;
  20239. }
  20240. return this;
  20241. };
  20242. /**
  20243. * Enables the edge rendering mode on the mesh.
  20244. * This mode makes the mesh edges visible
  20245. * @param epsilon defines the maximal distance between two angles to detect a face
  20246. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20247. * @returns the currentAbstractMesh
  20248. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20249. */
  20250. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20251. if (epsilon === void 0) { epsilon = 0.95; }
  20252. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20253. this.disableEdgesRendering();
  20254. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20255. return this;
  20256. };
  20257. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20258. /**
  20259. * Gets the edgesRenderer associated with the mesh
  20260. */
  20261. get: function () {
  20262. return this._edgesRenderer;
  20263. },
  20264. enumerable: true,
  20265. configurable: true
  20266. });
  20267. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20268. /**
  20269. * Returns true if the mesh is blocked. Implemented by child classes
  20270. */
  20271. get: function () {
  20272. return false;
  20273. },
  20274. enumerable: true,
  20275. configurable: true
  20276. });
  20277. /**
  20278. * Returns the mesh itself by default. Implemented by child classes
  20279. * @param camera defines the camera to use to pick the right LOD level
  20280. * @returns the currentAbstractMesh
  20281. */
  20282. AbstractMesh.prototype.getLOD = function (camera) {
  20283. return this;
  20284. };
  20285. /**
  20286. * Returns 0 by default. Implemented by child classes
  20287. * @returns an integer
  20288. */
  20289. AbstractMesh.prototype.getTotalVertices = function () {
  20290. return 0;
  20291. };
  20292. /**
  20293. * Returns null by default. Implemented by child classes
  20294. * @returns null
  20295. */
  20296. AbstractMesh.prototype.getIndices = function () {
  20297. return null;
  20298. };
  20299. /**
  20300. * Returns the array of the requested vertex data kind. Implemented by child classes
  20301. * @param kind defines the vertex data kind to use
  20302. * @returns null
  20303. */
  20304. AbstractMesh.prototype.getVerticesData = function (kind) {
  20305. return null;
  20306. };
  20307. /**
  20308. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20309. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20310. * Note that a new underlying VertexBuffer object is created each call.
  20311. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20312. * @param kind defines vertex data kind:
  20313. * * BABYLON.VertexBuffer.PositionKind
  20314. * * BABYLON.VertexBuffer.UVKind
  20315. * * BABYLON.VertexBuffer.UV2Kind
  20316. * * BABYLON.VertexBuffer.UV3Kind
  20317. * * BABYLON.VertexBuffer.UV4Kind
  20318. * * BABYLON.VertexBuffer.UV5Kind
  20319. * * BABYLON.VertexBuffer.UV6Kind
  20320. * * BABYLON.VertexBuffer.ColorKind
  20321. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20322. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20323. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20324. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20325. * @param data defines the data source
  20326. * @param updatable defines if the data must be flagged as updatable (or static)
  20327. * @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
  20328. * @returns the current mesh
  20329. */
  20330. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20331. return this;
  20332. };
  20333. /**
  20334. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20335. * If the mesh has no geometry, it is simply returned as it is.
  20336. * @param kind defines vertex data kind:
  20337. * * BABYLON.VertexBuffer.PositionKind
  20338. * * BABYLON.VertexBuffer.UVKind
  20339. * * BABYLON.VertexBuffer.UV2Kind
  20340. * * BABYLON.VertexBuffer.UV3Kind
  20341. * * BABYLON.VertexBuffer.UV4Kind
  20342. * * BABYLON.VertexBuffer.UV5Kind
  20343. * * BABYLON.VertexBuffer.UV6Kind
  20344. * * BABYLON.VertexBuffer.ColorKind
  20345. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20346. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20347. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20348. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20349. * @param data defines the data source
  20350. * @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
  20351. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20352. * @returns the current mesh
  20353. */
  20354. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20355. return this;
  20356. };
  20357. /**
  20358. * Sets the mesh indices,
  20359. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20360. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20361. * @param totalVertices Defines the total number of vertices
  20362. * @returns the current mesh
  20363. */
  20364. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20365. return this;
  20366. };
  20367. /**
  20368. * Gets a boolean indicating if specific vertex data is present
  20369. * @param kind defines the vertex data kind to use
  20370. * @returns true is data kind is present
  20371. */
  20372. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20373. return false;
  20374. };
  20375. /**
  20376. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20377. * @returns a BoundingInfo
  20378. */
  20379. AbstractMesh.prototype.getBoundingInfo = function () {
  20380. if (this._masterMesh) {
  20381. return this._masterMesh.getBoundingInfo();
  20382. }
  20383. if (!this._boundingInfo) {
  20384. // this._boundingInfo is being created here
  20385. this._updateBoundingInfo();
  20386. }
  20387. // cannot be null.
  20388. return this._boundingInfo;
  20389. };
  20390. /**
  20391. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20392. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20393. * @returns the current mesh
  20394. */
  20395. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20396. if (includeDescendants === void 0) { includeDescendants = true; }
  20397. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20398. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20399. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20400. if (maxDimension === 0) {
  20401. return this;
  20402. }
  20403. var scale = 1 / maxDimension;
  20404. this.scaling.scaleInPlace(scale);
  20405. return this;
  20406. };
  20407. /**
  20408. * Overwrite the current bounding info
  20409. * @param boundingInfo defines the new bounding info
  20410. * @returns the current mesh
  20411. */
  20412. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20413. this._boundingInfo = boundingInfo;
  20414. return this;
  20415. };
  20416. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20417. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20418. get: function () {
  20419. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20420. },
  20421. enumerable: true,
  20422. configurable: true
  20423. });
  20424. /** @hidden */
  20425. AbstractMesh.prototype._preActivate = function () {
  20426. };
  20427. /** @hidden */
  20428. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20429. };
  20430. /** @hidden */
  20431. AbstractMesh.prototype._activate = function (renderId) {
  20432. this._renderId = renderId;
  20433. };
  20434. /**
  20435. * Gets the current world matrix
  20436. * @returns a Matrix
  20437. */
  20438. AbstractMesh.prototype.getWorldMatrix = function () {
  20439. if (this._masterMesh) {
  20440. return this._masterMesh.getWorldMatrix();
  20441. }
  20442. return _super.prototype.getWorldMatrix.call(this);
  20443. };
  20444. /** @hidden */
  20445. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20446. if (this._masterMesh) {
  20447. return this._masterMesh._getWorldMatrixDeterminant();
  20448. }
  20449. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20450. };
  20451. // ================================== Point of View Movement =================================
  20452. /**
  20453. * Perform relative position change from the point of view of behind the front of the mesh.
  20454. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20455. * Supports definition of mesh facing forward or backward
  20456. * @param amountRight defines the distance on the right axis
  20457. * @param amountUp defines the distance on the up axis
  20458. * @param amountForward defines the distance on the forward axis
  20459. * @returns the current mesh
  20460. */
  20461. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20462. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20463. return this;
  20464. };
  20465. /**
  20466. * Calculate relative position change from the point of view of behind the front of the mesh.
  20467. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20468. * Supports definition of mesh facing forward or backward
  20469. * @param amountRight defines the distance on the right axis
  20470. * @param amountUp defines the distance on the up axis
  20471. * @param amountForward defines the distance on the forward axis
  20472. * @returns the new displacement vector
  20473. */
  20474. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20475. var rotMatrix = new BABYLON.Matrix();
  20476. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20477. rotQuaternion.toRotationMatrix(rotMatrix);
  20478. var translationDelta = BABYLON.Vector3.Zero();
  20479. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20481. return translationDelta;
  20482. };
  20483. // ================================== Point of View Rotation =================================
  20484. /**
  20485. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20486. * Supports definition of mesh facing forward or backward
  20487. * @param flipBack defines the flip
  20488. * @param twirlClockwise defines the twirl
  20489. * @param tiltRight defines the tilt
  20490. * @returns the current mesh
  20491. */
  20492. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20493. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20494. return this;
  20495. };
  20496. /**
  20497. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20498. * Supports definition of mesh facing forward or backward.
  20499. * @param flipBack defines the flip
  20500. * @param twirlClockwise defines the twirl
  20501. * @param tiltRight defines the tilt
  20502. * @returns the new rotation vector
  20503. */
  20504. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20505. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20506. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20507. };
  20508. /**
  20509. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20510. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20511. * @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
  20512. * @returns the new bounding vectors
  20513. */
  20514. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20515. if (includeDescendants === void 0) { includeDescendants = true; }
  20516. if (predicate === void 0) { predicate = null; }
  20517. // Ensures that all world matrix will be recomputed.
  20518. this.getScene().incrementRenderId();
  20519. this.computeWorldMatrix(true);
  20520. var min;
  20521. var max;
  20522. var boundingInfo = this.getBoundingInfo();
  20523. if (!this.subMeshes) {
  20524. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20525. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20526. }
  20527. else {
  20528. min = boundingInfo.boundingBox.minimumWorld;
  20529. max = boundingInfo.boundingBox.maximumWorld;
  20530. }
  20531. if (includeDescendants) {
  20532. var descendants = this.getDescendants(false);
  20533. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20534. var descendant = descendants_1[_i];
  20535. var childMesh = descendant;
  20536. childMesh.computeWorldMatrix(true);
  20537. // Filters meshes based on custom predicate function.
  20538. if (predicate && !predicate(childMesh)) {
  20539. continue;
  20540. }
  20541. //make sure we have the needed params to get mix and max
  20542. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20543. continue;
  20544. }
  20545. var childBoundingInfo = childMesh.getBoundingInfo();
  20546. var boundingBox = childBoundingInfo.boundingBox;
  20547. var minBox = boundingBox.minimumWorld;
  20548. var maxBox = boundingBox.maximumWorld;
  20549. BABYLON.Tools.CheckExtends(minBox, min, max);
  20550. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20551. }
  20552. }
  20553. return {
  20554. min: min,
  20555. max: max
  20556. };
  20557. };
  20558. /** @hidden */
  20559. AbstractMesh.prototype._updateBoundingInfo = function () {
  20560. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20561. this._boundingInfo.update(this.worldMatrixFromCache);
  20562. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20563. return this;
  20564. };
  20565. /** @hidden */
  20566. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20567. if (!this.subMeshes) {
  20568. return this;
  20569. }
  20570. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20571. var subMesh = this.subMeshes[subIndex];
  20572. if (!subMesh.IsGlobal) {
  20573. subMesh.updateBoundingInfo(matrix);
  20574. }
  20575. }
  20576. return this;
  20577. };
  20578. /** @hidden */
  20579. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20580. // Bounding info
  20581. this._updateBoundingInfo();
  20582. };
  20583. /**
  20584. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20585. * A mesh is in the frustum if its bounding box intersects the frustum
  20586. * @param frustumPlanes defines the frustum to test
  20587. * @returns true if the mesh is in the frustum planes
  20588. */
  20589. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20590. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20591. };
  20592. /**
  20593. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20594. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20595. * @param frustumPlanes defines the frustum to test
  20596. * @returns true if the mesh is completely in the frustum planes
  20597. */
  20598. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20599. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20600. };
  20601. /**
  20602. * True if the mesh intersects another mesh or a SolidParticle object
  20603. * @param mesh defines a target mesh or SolidParticle to test
  20604. * @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)
  20605. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20606. * @returns true if there is an intersection
  20607. */
  20608. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20609. if (precise === void 0) { precise = false; }
  20610. if (!this._boundingInfo || !mesh._boundingInfo) {
  20611. return false;
  20612. }
  20613. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20614. return true;
  20615. }
  20616. if (includeDescendants) {
  20617. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20618. var child = _a[_i];
  20619. if (child.intersectsMesh(mesh, precise, true)) {
  20620. return true;
  20621. }
  20622. }
  20623. }
  20624. return false;
  20625. };
  20626. /**
  20627. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20628. * @param point defines the point to test
  20629. * @returns true if there is an intersection
  20630. */
  20631. AbstractMesh.prototype.intersectsPoint = function (point) {
  20632. if (!this._boundingInfo) {
  20633. return false;
  20634. }
  20635. return this._boundingInfo.intersectsPoint(point);
  20636. };
  20637. /**
  20638. * Gets the current physics impostor
  20639. * @see http://doc.babylonjs.com/features/physics_engine
  20640. * @returns a physics impostor or null
  20641. */
  20642. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20643. return this.physicsImpostor;
  20644. };
  20645. /**
  20646. * Gets the position of the current mesh in camera space
  20647. * @param camera defines the camera to use
  20648. * @returns a position
  20649. */
  20650. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20651. if (camera === void 0) { camera = null; }
  20652. if (!camera) {
  20653. camera = this.getScene().activeCamera;
  20654. }
  20655. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20656. };
  20657. /**
  20658. * Returns the distance from the mesh to the active camera
  20659. * @param camera defines the camera to use
  20660. * @returns the distance
  20661. */
  20662. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20663. if (camera === void 0) { camera = null; }
  20664. if (!camera) {
  20665. camera = this.getScene().activeCamera;
  20666. }
  20667. return this.absolutePosition.subtract(camera.position).length();
  20668. };
  20669. /**
  20670. * Apply a physic impulse to the mesh
  20671. * @param force defines the force to apply
  20672. * @param contactPoint defines where to apply the force
  20673. * @returns the current mesh
  20674. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20675. */
  20676. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20677. if (!this.physicsImpostor) {
  20678. return this;
  20679. }
  20680. this.physicsImpostor.applyImpulse(force, contactPoint);
  20681. return this;
  20682. };
  20683. /**
  20684. * Creates a physic joint between two meshes
  20685. * @param otherMesh defines the other mesh to use
  20686. * @param pivot1 defines the pivot to use on this mesh
  20687. * @param pivot2 defines the pivot to use on the other mesh
  20688. * @param options defines additional options (can be plugin dependent)
  20689. * @returns the current mesh
  20690. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20691. */
  20692. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20693. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20694. return this;
  20695. }
  20696. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20697. mainPivot: pivot1,
  20698. connectedPivot: pivot2,
  20699. nativeParams: options
  20700. });
  20701. return this;
  20702. };
  20703. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20704. // Collisions
  20705. /**
  20706. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20707. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20708. */
  20709. get: function () {
  20710. return this._checkCollisions;
  20711. },
  20712. set: function (collisionEnabled) {
  20713. this._checkCollisions = collisionEnabled;
  20714. if (this.getScene().workerCollisions) {
  20715. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20716. }
  20717. },
  20718. enumerable: true,
  20719. configurable: true
  20720. });
  20721. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20722. /**
  20723. * Gets Collider object used to compute collisions (not physics)
  20724. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20725. */
  20726. get: function () {
  20727. return this._collider;
  20728. },
  20729. enumerable: true,
  20730. configurable: true
  20731. });
  20732. /**
  20733. * Move the mesh using collision engine
  20734. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20735. * @param displacement defines the requested displacement vector
  20736. * @returns the current mesh
  20737. */
  20738. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20739. var globalPosition = this.getAbsolutePosition();
  20740. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20741. if (!this._collider) {
  20742. this._collider = new BABYLON.Collider();
  20743. }
  20744. this._collider._radius = this.ellipsoid;
  20745. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20746. return this;
  20747. };
  20748. // Submeshes octree
  20749. /**
  20750. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20751. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20752. * @param maxCapacity defines the maximum size of each block (64 by default)
  20753. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20754. * @returns the new octree
  20755. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20756. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20757. */
  20758. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20759. if (maxCapacity === void 0) { maxCapacity = 64; }
  20760. if (maxDepth === void 0) { maxDepth = 2; }
  20761. if (!this._submeshesOctree) {
  20762. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20763. }
  20764. this.computeWorldMatrix(true);
  20765. var boundingInfo = this.getBoundingInfo();
  20766. // Update octree
  20767. var bbox = boundingInfo.boundingBox;
  20768. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20769. return this._submeshesOctree;
  20770. };
  20771. // Collisions
  20772. /** @hidden */
  20773. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20774. this._generatePointsArray();
  20775. if (!this._positions) {
  20776. return this;
  20777. }
  20778. // Transformation
  20779. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20780. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20781. subMesh._lastColliderWorldVertices = [];
  20782. subMesh._trianglePlanes = [];
  20783. var start = subMesh.verticesStart;
  20784. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20785. for (var i = start; i < end; i++) {
  20786. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20787. }
  20788. }
  20789. // Collide
  20790. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20791. if (collider.collisionFound) {
  20792. collider.collidedMesh = this;
  20793. }
  20794. return this;
  20795. };
  20796. /** @hidden */
  20797. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20798. var subMeshes;
  20799. var len;
  20800. // Octrees
  20801. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20802. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20803. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20804. len = intersections.length;
  20805. subMeshes = intersections.data;
  20806. }
  20807. else {
  20808. subMeshes = this.subMeshes;
  20809. len = subMeshes.length;
  20810. }
  20811. for (var index = 0; index < len; index++) {
  20812. var subMesh = subMeshes[index];
  20813. // Bounding test
  20814. if (len > 1 && !subMesh._checkCollision(collider))
  20815. continue;
  20816. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20817. }
  20818. return this;
  20819. };
  20820. /** @hidden */
  20821. AbstractMesh.prototype._checkCollision = function (collider) {
  20822. // Bounding box test
  20823. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20824. return this;
  20825. // Transformation matrix
  20826. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20827. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20828. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20829. return this;
  20830. };
  20831. // Picking
  20832. /** @hidden */
  20833. AbstractMesh.prototype._generatePointsArray = function () {
  20834. return false;
  20835. };
  20836. /**
  20837. * Checks if the passed Ray intersects with the mesh
  20838. * @param ray defines the ray to use
  20839. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20840. * @returns the picking info
  20841. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20842. */
  20843. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20844. var pickingInfo = new BABYLON.PickingInfo();
  20845. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20846. return pickingInfo;
  20847. }
  20848. if (!this._generatePointsArray()) {
  20849. return pickingInfo;
  20850. }
  20851. var intersectInfo = null;
  20852. // Octrees
  20853. var subMeshes;
  20854. var len;
  20855. if (this._submeshesOctree && this.useOctreeForPicking) {
  20856. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20857. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20858. len = intersections.length;
  20859. subMeshes = intersections.data;
  20860. }
  20861. else {
  20862. subMeshes = this.subMeshes;
  20863. len = subMeshes.length;
  20864. }
  20865. for (var index = 0; index < len; index++) {
  20866. var subMesh = subMeshes[index];
  20867. // Bounding test
  20868. if (len > 1 && !subMesh.canIntersects(ray))
  20869. continue;
  20870. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20871. if (currentIntersectInfo) {
  20872. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20873. intersectInfo = currentIntersectInfo;
  20874. intersectInfo.subMeshId = index;
  20875. if (fastCheck) {
  20876. break;
  20877. }
  20878. }
  20879. }
  20880. }
  20881. if (intersectInfo) {
  20882. // Get picked point
  20883. var world = this.getWorldMatrix();
  20884. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20885. var direction = ray.direction.clone();
  20886. direction = direction.scale(intersectInfo.distance);
  20887. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20888. var pickedPoint = worldOrigin.add(worldDirection);
  20889. // Return result
  20890. pickingInfo.hit = true;
  20891. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20892. pickingInfo.pickedPoint = pickedPoint;
  20893. pickingInfo.pickedMesh = this;
  20894. pickingInfo.bu = intersectInfo.bu || 0;
  20895. pickingInfo.bv = intersectInfo.bv || 0;
  20896. pickingInfo.faceId = intersectInfo.faceId;
  20897. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20898. return pickingInfo;
  20899. }
  20900. return pickingInfo;
  20901. };
  20902. /**
  20903. * Clones the current mesh
  20904. * @param name defines the mesh name
  20905. * @param newParent defines the new mesh parent
  20906. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20907. * @returns the new mesh
  20908. */
  20909. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20910. return null;
  20911. };
  20912. /**
  20913. * Disposes all the submeshes of the current meshnp
  20914. * @returns the current mesh
  20915. */
  20916. AbstractMesh.prototype.releaseSubMeshes = function () {
  20917. if (this.subMeshes) {
  20918. while (this.subMeshes.length) {
  20919. this.subMeshes[0].dispose();
  20920. }
  20921. }
  20922. else {
  20923. this.subMeshes = new Array();
  20924. }
  20925. return this;
  20926. };
  20927. /**
  20928. * Releases resources associated with this abstract mesh.
  20929. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20930. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20931. */
  20932. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20933. var _this = this;
  20934. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20935. var index;
  20936. // Smart Array Retainers.
  20937. this.getScene().freeActiveMeshes();
  20938. this.getScene().freeRenderingGroups();
  20939. // Action manager
  20940. if (this.actionManager !== undefined && this.actionManager !== null) {
  20941. this.actionManager.dispose();
  20942. this.actionManager = null;
  20943. }
  20944. // Skeleton
  20945. this._skeleton = null;
  20946. // Physics
  20947. if (this.physicsImpostor) {
  20948. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20949. }
  20950. // Intersections in progress
  20951. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20952. var other = this._intersectionsInProgress[index];
  20953. var pos = other._intersectionsInProgress.indexOf(this);
  20954. other._intersectionsInProgress.splice(pos, 1);
  20955. }
  20956. this._intersectionsInProgress = [];
  20957. // Lights
  20958. var lights = this.getScene().lights;
  20959. lights.forEach(function (light) {
  20960. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20961. if (meshIndex !== -1) {
  20962. light.includedOnlyMeshes.splice(meshIndex, 1);
  20963. }
  20964. meshIndex = light.excludedMeshes.indexOf(_this);
  20965. if (meshIndex !== -1) {
  20966. light.excludedMeshes.splice(meshIndex, 1);
  20967. }
  20968. // Shadow generators
  20969. var generator = light.getShadowGenerator();
  20970. if (generator) {
  20971. var shadowMap = generator.getShadowMap();
  20972. if (shadowMap && shadowMap.renderList) {
  20973. meshIndex = shadowMap.renderList.indexOf(_this);
  20974. if (meshIndex !== -1) {
  20975. shadowMap.renderList.splice(meshIndex, 1);
  20976. }
  20977. }
  20978. }
  20979. });
  20980. // Edges
  20981. if (this._edgesRenderer) {
  20982. this._edgesRenderer.dispose();
  20983. this._edgesRenderer = null;
  20984. }
  20985. // SubMeshes
  20986. if (this.getClassName() !== "InstancedMesh") {
  20987. this.releaseSubMeshes();
  20988. }
  20989. // Octree
  20990. var sceneOctree = this.getScene().selectionOctree;
  20991. if (sceneOctree !== undefined && sceneOctree !== null) {
  20992. var index = sceneOctree.dynamicContent.indexOf(this);
  20993. if (index !== -1) {
  20994. sceneOctree.dynamicContent.splice(index, 1);
  20995. }
  20996. }
  20997. // Query
  20998. var engine = this.getScene().getEngine();
  20999. if (this._occlusionQuery) {
  21000. this._isOcclusionQueryInProgress = false;
  21001. engine.deleteQuery(this._occlusionQuery);
  21002. this._occlusionQuery = null;
  21003. }
  21004. // Engine
  21005. engine.wipeCaches();
  21006. // Remove from scene
  21007. this.getScene().removeMesh(this);
  21008. if (disposeMaterialAndTextures) {
  21009. if (this.material) {
  21010. this.material.dispose(false, true);
  21011. }
  21012. }
  21013. if (!doNotRecurse) {
  21014. // Particles
  21015. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21016. if (this.getScene().particleSystems[index].emitter === this) {
  21017. this.getScene().particleSystems[index].dispose();
  21018. index--;
  21019. }
  21020. }
  21021. }
  21022. // facet data
  21023. if (this._facetDataEnabled) {
  21024. this.disableFacetData();
  21025. }
  21026. this.onAfterWorldMatrixUpdateObservable.clear();
  21027. this.onCollideObservable.clear();
  21028. this.onCollisionPositionChangeObservable.clear();
  21029. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21030. };
  21031. /**
  21032. * Adds the passed mesh as a child to the current mesh
  21033. * @param mesh defines the child mesh
  21034. * @returns the current mesh
  21035. */
  21036. AbstractMesh.prototype.addChild = function (mesh) {
  21037. mesh.setParent(this);
  21038. return this;
  21039. };
  21040. /**
  21041. * Removes the passed mesh from the current mesh children list
  21042. * @param mesh defines the child mesh
  21043. * @returns the current mesh
  21044. */
  21045. AbstractMesh.prototype.removeChild = function (mesh) {
  21046. mesh.setParent(null);
  21047. return this;
  21048. };
  21049. // Facet data
  21050. /** @hidden */
  21051. AbstractMesh.prototype._initFacetData = function () {
  21052. if (!this._facetNormals) {
  21053. this._facetNormals = new Array();
  21054. }
  21055. if (!this._facetPositions) {
  21056. this._facetPositions = new Array();
  21057. }
  21058. if (!this._facetPartitioning) {
  21059. this._facetPartitioning = new Array();
  21060. }
  21061. this._facetNb = (this.getIndices().length / 3) | 0;
  21062. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21063. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21064. for (var f = 0; f < this._facetNb; f++) {
  21065. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21066. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21067. }
  21068. this._facetDataEnabled = true;
  21069. return this;
  21070. };
  21071. /**
  21072. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21073. * This method can be called within the render loop.
  21074. * 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
  21075. * @returns the current mesh
  21076. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21077. */
  21078. AbstractMesh.prototype.updateFacetData = function () {
  21079. if (!this._facetDataEnabled) {
  21080. this._initFacetData();
  21081. }
  21082. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21083. var indices = this.getIndices();
  21084. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21085. var bInfo = this.getBoundingInfo();
  21086. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21087. // init arrays, matrix and sort function on first call
  21088. this._facetDepthSortEnabled = true;
  21089. if (indices instanceof Uint16Array) {
  21090. this._depthSortedIndices = new Uint16Array(indices);
  21091. }
  21092. else if (indices instanceof Uint32Array) {
  21093. this._depthSortedIndices = new Uint32Array(indices);
  21094. }
  21095. else {
  21096. var needs32bits = false;
  21097. for (var i = 0; i < indices.length; i++) {
  21098. if (indices[i] > 65535) {
  21099. needs32bits = true;
  21100. break;
  21101. }
  21102. }
  21103. if (needs32bits) {
  21104. this._depthSortedIndices = new Uint32Array(indices);
  21105. }
  21106. else {
  21107. this._depthSortedIndices = new Uint16Array(indices);
  21108. }
  21109. }
  21110. this._facetDepthSortFunction = function (f1, f2) {
  21111. return (f2.sqDistance - f1.sqDistance);
  21112. };
  21113. if (!this._facetDepthSortFrom) {
  21114. var camera = this.getScene().activeCamera;
  21115. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21116. }
  21117. this._depthSortedFacets = [];
  21118. for (var f = 0; f < this._facetNb; f++) {
  21119. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21120. this._depthSortedFacets.push(depthSortedFacet);
  21121. }
  21122. this._invertedMatrix = BABYLON.Matrix.Identity();
  21123. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21124. }
  21125. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21126. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21127. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21128. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21129. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21130. this._subDiv.max = this._partitioningSubdivisions;
  21131. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21132. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21133. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21134. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21135. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21136. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21137. // set the parameters for ComputeNormals()
  21138. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21139. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21140. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21141. this._facetParameters.bInfo = bInfo;
  21142. this._facetParameters.bbSize = this._bbSize;
  21143. this._facetParameters.subDiv = this._subDiv;
  21144. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21145. this._facetParameters.depthSort = this._facetDepthSort;
  21146. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21147. this.computeWorldMatrix(true);
  21148. this._worldMatrix.invertToRef(this._invertedMatrix);
  21149. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21150. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21151. }
  21152. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21153. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21154. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21155. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21156. var l = (this._depthSortedIndices.length / 3) | 0;
  21157. for (var f = 0; f < l; f++) {
  21158. var sind = this._depthSortedFacets[f].ind;
  21159. this._depthSortedIndices[f * 3] = indices[sind];
  21160. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21161. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21162. }
  21163. this.updateIndices(this._depthSortedIndices);
  21164. }
  21165. return this;
  21166. };
  21167. /**
  21168. * Returns the facetLocalNormals array.
  21169. * The normals are expressed in the mesh local spac
  21170. * @returns an array of Vector3
  21171. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21172. */
  21173. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21174. if (!this._facetNormals) {
  21175. this.updateFacetData();
  21176. }
  21177. return this._facetNormals;
  21178. };
  21179. /**
  21180. * Returns the facetLocalPositions array.
  21181. * The facet positions are expressed in the mesh local space
  21182. * @returns an array of Vector3
  21183. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21184. */
  21185. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21186. if (!this._facetPositions) {
  21187. this.updateFacetData();
  21188. }
  21189. return this._facetPositions;
  21190. };
  21191. /**
  21192. * Returns the facetLocalPartioning array
  21193. * @returns an array of array of numbers
  21194. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21195. */
  21196. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21197. if (!this._facetPartitioning) {
  21198. this.updateFacetData();
  21199. }
  21200. return this._facetPartitioning;
  21201. };
  21202. /**
  21203. * Returns the i-th facet position in the world system.
  21204. * This method allocates a new Vector3 per call
  21205. * @param i defines the facet index
  21206. * @returns a new Vector3
  21207. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21208. */
  21209. AbstractMesh.prototype.getFacetPosition = function (i) {
  21210. var pos = BABYLON.Vector3.Zero();
  21211. this.getFacetPositionToRef(i, pos);
  21212. return pos;
  21213. };
  21214. /**
  21215. * Sets the reference Vector3 with the i-th facet position in the world system
  21216. * @param i defines the facet index
  21217. * @param ref defines the target vector
  21218. * @returns the current mesh
  21219. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21220. */
  21221. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21222. var localPos = (this.getFacetLocalPositions())[i];
  21223. var world = this.getWorldMatrix();
  21224. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21225. return this;
  21226. };
  21227. /**
  21228. * Returns the i-th facet normal in the world system.
  21229. * This method allocates a new Vector3 per call
  21230. * @param i defines the facet index
  21231. * @returns a new Vector3
  21232. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21233. */
  21234. AbstractMesh.prototype.getFacetNormal = function (i) {
  21235. var norm = BABYLON.Vector3.Zero();
  21236. this.getFacetNormalToRef(i, norm);
  21237. return norm;
  21238. };
  21239. /**
  21240. * Sets the reference Vector3 with the i-th facet normal in the world system
  21241. * @param i defines the facet index
  21242. * @param ref defines the target vector
  21243. * @returns the current mesh
  21244. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21245. */
  21246. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21247. var localNorm = (this.getFacetLocalNormals())[i];
  21248. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21249. return this;
  21250. };
  21251. /**
  21252. * 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)
  21253. * @param x defines x coordinate
  21254. * @param y defines y coordinate
  21255. * @param z defines z coordinate
  21256. * @returns the array of facet indexes
  21257. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21258. */
  21259. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21260. var bInfo = this.getBoundingInfo();
  21261. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21262. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21263. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21264. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21265. return null;
  21266. }
  21267. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21268. };
  21269. /**
  21270. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21271. * @param projected sets as the (x,y,z) world projection on the facet
  21272. * @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
  21273. * @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
  21274. * @param x defines x coordinate
  21275. * @param y defines y coordinate
  21276. * @param z defines z coordinate
  21277. * @returns the face index if found (or null instead)
  21278. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21279. */
  21280. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21281. if (checkFace === void 0) { checkFace = false; }
  21282. if (facing === void 0) { facing = true; }
  21283. var world = this.getWorldMatrix();
  21284. var invMat = BABYLON.Tmp.Matrix[5];
  21285. world.invertToRef(invMat);
  21286. var invVect = BABYLON.Tmp.Vector3[8];
  21287. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21288. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21289. if (projected) {
  21290. // tranform the local computed projected vector to world coordinates
  21291. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21292. }
  21293. return closest;
  21294. };
  21295. /**
  21296. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21297. * @param projected sets as the (x,y,z) local projection on the facet
  21298. * @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
  21299. * @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
  21300. * @param x defines x coordinate
  21301. * @param y defines y coordinate
  21302. * @param z defines z coordinate
  21303. * @returns the face index if found (or null instead)
  21304. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21305. */
  21306. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21307. if (checkFace === void 0) { checkFace = false; }
  21308. if (facing === void 0) { facing = true; }
  21309. var closest = null;
  21310. var tmpx = 0.0;
  21311. var tmpy = 0.0;
  21312. var tmpz = 0.0;
  21313. var d = 0.0; // tmp dot facet normal * facet position
  21314. var t0 = 0.0;
  21315. var projx = 0.0;
  21316. var projy = 0.0;
  21317. var projz = 0.0;
  21318. // Get all the facets in the same partitioning block than (x, y, z)
  21319. var facetPositions = this.getFacetLocalPositions();
  21320. var facetNormals = this.getFacetLocalNormals();
  21321. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21322. if (!facetsInBlock) {
  21323. return null;
  21324. }
  21325. // Get the closest facet to (x, y, z)
  21326. var shortest = Number.MAX_VALUE; // init distance vars
  21327. var tmpDistance = shortest;
  21328. var fib; // current facet in the block
  21329. var norm; // current facet normal
  21330. var p0; // current facet barycenter position
  21331. // loop on all the facets in the current partitioning block
  21332. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21333. fib = facetsInBlock[idx];
  21334. norm = facetNormals[fib];
  21335. p0 = facetPositions[fib];
  21336. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21337. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21338. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21339. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21340. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21341. projx = x + norm.x * t0;
  21342. projy = y + norm.y * t0;
  21343. projz = z + norm.z * t0;
  21344. tmpx = projx - x;
  21345. tmpy = projy - y;
  21346. tmpz = projz - z;
  21347. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21348. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21349. shortest = tmpDistance;
  21350. closest = fib;
  21351. if (projected) {
  21352. projected.x = projx;
  21353. projected.y = projy;
  21354. projected.z = projz;
  21355. }
  21356. }
  21357. }
  21358. }
  21359. return closest;
  21360. };
  21361. /**
  21362. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21363. * @returns the parameters
  21364. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21365. */
  21366. AbstractMesh.prototype.getFacetDataParameters = function () {
  21367. return this._facetParameters;
  21368. };
  21369. /**
  21370. * Disables the feature FacetData and frees the related memory
  21371. * @returns the current mesh
  21372. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21373. */
  21374. AbstractMesh.prototype.disableFacetData = function () {
  21375. if (this._facetDataEnabled) {
  21376. this._facetDataEnabled = false;
  21377. this._facetPositions = new Array();
  21378. this._facetNormals = new Array();
  21379. this._facetPartitioning = new Array();
  21380. this._facetParameters = null;
  21381. this._depthSortedIndices = new Uint32Array(0);
  21382. }
  21383. return this;
  21384. };
  21385. /**
  21386. * Updates the AbstractMesh indices array
  21387. * @param indices defines the data source
  21388. * @returns the current mesh
  21389. */
  21390. AbstractMesh.prototype.updateIndices = function (indices) {
  21391. return this;
  21392. };
  21393. /**
  21394. * Creates new normals data for the mesh
  21395. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21396. * @returns the current mesh
  21397. */
  21398. AbstractMesh.prototype.createNormals = function (updatable) {
  21399. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21400. var indices = this.getIndices();
  21401. var normals;
  21402. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21403. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21404. }
  21405. else {
  21406. normals = [];
  21407. }
  21408. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21409. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21410. return this;
  21411. };
  21412. /**
  21413. * Align the mesh with a normal
  21414. * @param normal defines the normal to use
  21415. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21416. * @returns the current mesh
  21417. */
  21418. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21419. if (!upDirection) {
  21420. upDirection = BABYLON.Axis.Y;
  21421. }
  21422. var axisX = BABYLON.Tmp.Vector3[0];
  21423. var axisZ = BABYLON.Tmp.Vector3[1];
  21424. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21425. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21426. if (this.rotationQuaternion) {
  21427. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21428. }
  21429. else {
  21430. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21431. }
  21432. return this;
  21433. };
  21434. /** @hidden */
  21435. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21436. var engine = this.getEngine();
  21437. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21438. this._isOccluded = false;
  21439. return;
  21440. }
  21441. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21442. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21443. if (isOcclusionQueryAvailable) {
  21444. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21445. this._isOcclusionQueryInProgress = false;
  21446. this._occlusionInternalRetryCounter = 0;
  21447. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21448. }
  21449. else {
  21450. this._occlusionInternalRetryCounter++;
  21451. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21452. this._isOcclusionQueryInProgress = false;
  21453. this._occlusionInternalRetryCounter = 0;
  21454. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21455. // if strict continue the last state of the object.
  21456. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21457. }
  21458. else {
  21459. return;
  21460. }
  21461. }
  21462. }
  21463. var scene = this.getScene();
  21464. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21465. if (!this._occlusionQuery) {
  21466. this._occlusionQuery = engine.createQuery();
  21467. }
  21468. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21469. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21470. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21471. this._isOcclusionQueryInProgress = true;
  21472. };
  21473. /** No occlusion */
  21474. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21475. /** Occlusion set to optimisitic */
  21476. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21477. /** Occlusion set to strict */
  21478. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21479. /** Use an accurante occlusion algorithm */
  21480. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21481. /** Use a conservative occlusion algorithm */
  21482. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21483. return AbstractMesh;
  21484. }(BABYLON.TransformNode));
  21485. BABYLON.AbstractMesh = AbstractMesh;
  21486. })(BABYLON || (BABYLON = {}));
  21487. //# sourceMappingURL=babylon.abstractMesh.js.map
  21488. var BABYLON;
  21489. (function (BABYLON) {
  21490. /**
  21491. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21492. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21493. * 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.
  21494. */
  21495. var Light = /** @class */ (function (_super) {
  21496. __extends(Light, _super);
  21497. /**
  21498. * Creates a Light object in the scene.
  21499. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21500. * @param name The firendly name of the light
  21501. * @param scene The scene the light belongs too
  21502. */
  21503. function Light(name, scene) {
  21504. var _this = _super.call(this, name, scene) || this;
  21505. /**
  21506. * Diffuse gives the basic color to an object.
  21507. */
  21508. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21509. /**
  21510. * Specular produces a highlight color on an object.
  21511. * Note: This is note affecting PBR materials.
  21512. */
  21513. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21514. /**
  21515. * Strength of the light.
  21516. * Note: By default it is define in the framework own unit.
  21517. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21518. */
  21519. _this.intensity = 1.0;
  21520. /**
  21521. * Defines how far from the source the light is impacting in scene units.
  21522. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21523. */
  21524. _this.range = Number.MAX_VALUE;
  21525. /**
  21526. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21527. * of light.
  21528. */
  21529. _this._photometricScale = 1.0;
  21530. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21531. _this._radius = 0.00001;
  21532. /**
  21533. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21534. * exceeding the number allowed of the materials.
  21535. */
  21536. _this.renderPriority = 0;
  21537. _this._shadowEnabled = true;
  21538. _this._excludeWithLayerMask = 0;
  21539. _this._includeOnlyWithLayerMask = 0;
  21540. _this._lightmapMode = 0;
  21541. /**
  21542. * @hidden Internal use only.
  21543. */
  21544. _this._excludedMeshesIds = new Array();
  21545. /**
  21546. * @hidden Internal use only.
  21547. */
  21548. _this._includedOnlyMeshesIds = new Array();
  21549. _this.getScene().addLight(_this);
  21550. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21551. _this._buildUniformLayout();
  21552. _this.includedOnlyMeshes = new Array();
  21553. _this.excludedMeshes = new Array();
  21554. _this._resyncMeshes();
  21555. return _this;
  21556. }
  21557. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21558. /**
  21559. * If every light affecting the material is in this lightmapMode,
  21560. * material.lightmapTexture adds or multiplies
  21561. * (depends on material.useLightmapAsShadowmap)
  21562. * after every other light calculations.
  21563. */
  21564. get: function () {
  21565. return Light._LIGHTMAP_DEFAULT;
  21566. },
  21567. enumerable: true,
  21568. configurable: true
  21569. });
  21570. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21571. /**
  21572. * material.lightmapTexture as only diffuse lighting from this light
  21573. * adds only specular lighting from this light
  21574. * adds dynamic shadows
  21575. */
  21576. get: function () {
  21577. return Light._LIGHTMAP_SPECULAR;
  21578. },
  21579. enumerable: true,
  21580. configurable: true
  21581. });
  21582. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21583. /**
  21584. * material.lightmapTexture as only lighting
  21585. * no light calculation from this light
  21586. * only adds dynamic shadows from this light
  21587. */
  21588. get: function () {
  21589. return Light._LIGHTMAP_SHADOWSONLY;
  21590. },
  21591. enumerable: true,
  21592. configurable: true
  21593. });
  21594. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21595. /**
  21596. * Each light type uses the default quantity according to its type:
  21597. * point/spot lights use luminous intensity
  21598. * directional lights use illuminance
  21599. */
  21600. get: function () {
  21601. return Light._INTENSITYMODE_AUTOMATIC;
  21602. },
  21603. enumerable: true,
  21604. configurable: true
  21605. });
  21606. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21607. /**
  21608. * lumen (lm)
  21609. */
  21610. get: function () {
  21611. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21612. },
  21613. enumerable: true,
  21614. configurable: true
  21615. });
  21616. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21617. /**
  21618. * candela (lm/sr)
  21619. */
  21620. get: function () {
  21621. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21622. },
  21623. enumerable: true,
  21624. configurable: true
  21625. });
  21626. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21627. /**
  21628. * lux (lm/m^2)
  21629. */
  21630. get: function () {
  21631. return Light._INTENSITYMODE_ILLUMINANCE;
  21632. },
  21633. enumerable: true,
  21634. configurable: true
  21635. });
  21636. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21637. /**
  21638. * nit (cd/m^2)
  21639. */
  21640. get: function () {
  21641. return Light._INTENSITYMODE_LUMINANCE;
  21642. },
  21643. enumerable: true,
  21644. configurable: true
  21645. });
  21646. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21647. /**
  21648. * Light type const id of the point light.
  21649. */
  21650. get: function () {
  21651. return Light._LIGHTTYPEID_POINTLIGHT;
  21652. },
  21653. enumerable: true,
  21654. configurable: true
  21655. });
  21656. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21657. /**
  21658. * Light type const id of the directional light.
  21659. */
  21660. get: function () {
  21661. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21662. },
  21663. enumerable: true,
  21664. configurable: true
  21665. });
  21666. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21667. /**
  21668. * Light type const id of the spot light.
  21669. */
  21670. get: function () {
  21671. return Light._LIGHTTYPEID_SPOTLIGHT;
  21672. },
  21673. enumerable: true,
  21674. configurable: true
  21675. });
  21676. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21677. /**
  21678. * Light type const id of the hemispheric light.
  21679. */
  21680. get: function () {
  21681. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21682. },
  21683. enumerable: true,
  21684. configurable: true
  21685. });
  21686. Object.defineProperty(Light.prototype, "intensityMode", {
  21687. /**
  21688. * Gets the photometric scale used to interpret the intensity.
  21689. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21690. */
  21691. get: function () {
  21692. return this._intensityMode;
  21693. },
  21694. /**
  21695. * Sets the photometric scale used to interpret the intensity.
  21696. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21697. */
  21698. set: function (value) {
  21699. this._intensityMode = value;
  21700. this._computePhotometricScale();
  21701. },
  21702. enumerable: true,
  21703. configurable: true
  21704. });
  21705. ;
  21706. ;
  21707. Object.defineProperty(Light.prototype, "radius", {
  21708. /**
  21709. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21710. */
  21711. get: function () {
  21712. return this._radius;
  21713. },
  21714. /**
  21715. * sets the light radius used by PBR Materials to simulate soft area lights.
  21716. */
  21717. set: function (value) {
  21718. this._radius = value;
  21719. this._computePhotometricScale();
  21720. },
  21721. enumerable: true,
  21722. configurable: true
  21723. });
  21724. ;
  21725. ;
  21726. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21727. /**
  21728. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21729. * the current shadow generator.
  21730. */
  21731. get: function () {
  21732. return this._shadowEnabled;
  21733. },
  21734. /**
  21735. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21736. * the current shadow generator.
  21737. */
  21738. set: function (value) {
  21739. if (this._shadowEnabled === value) {
  21740. return;
  21741. }
  21742. this._shadowEnabled = value;
  21743. this._markMeshesAsLightDirty();
  21744. },
  21745. enumerable: true,
  21746. configurable: true
  21747. });
  21748. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21749. /**
  21750. * Gets the only meshes impacted by this light.
  21751. */
  21752. get: function () {
  21753. return this._includedOnlyMeshes;
  21754. },
  21755. /**
  21756. * Sets the only meshes impacted by this light.
  21757. */
  21758. set: function (value) {
  21759. this._includedOnlyMeshes = value;
  21760. this._hookArrayForIncludedOnly(value);
  21761. },
  21762. enumerable: true,
  21763. configurable: true
  21764. });
  21765. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21766. /**
  21767. * Gets the meshes not impacted by this light.
  21768. */
  21769. get: function () {
  21770. return this._excludedMeshes;
  21771. },
  21772. /**
  21773. * Sets the meshes not impacted by this light.
  21774. */
  21775. set: function (value) {
  21776. this._excludedMeshes = value;
  21777. this._hookArrayForExcluded(value);
  21778. },
  21779. enumerable: true,
  21780. configurable: true
  21781. });
  21782. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21783. /**
  21784. * Gets the layer id use to find what meshes are not impacted by the light.
  21785. * Inactive if 0
  21786. */
  21787. get: function () {
  21788. return this._excludeWithLayerMask;
  21789. },
  21790. /**
  21791. * Sets the layer id use to find what meshes are not impacted by the light.
  21792. * Inactive if 0
  21793. */
  21794. set: function (value) {
  21795. this._excludeWithLayerMask = value;
  21796. this._resyncMeshes();
  21797. },
  21798. enumerable: true,
  21799. configurable: true
  21800. });
  21801. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21802. /**
  21803. * Gets the layer id use to find what meshes are impacted by the light.
  21804. * Inactive if 0
  21805. */
  21806. get: function () {
  21807. return this._includeOnlyWithLayerMask;
  21808. },
  21809. /**
  21810. * Sets the layer id use to find what meshes are impacted by the light.
  21811. * Inactive if 0
  21812. */
  21813. set: function (value) {
  21814. this._includeOnlyWithLayerMask = value;
  21815. this._resyncMeshes();
  21816. },
  21817. enumerable: true,
  21818. configurable: true
  21819. });
  21820. Object.defineProperty(Light.prototype, "lightmapMode", {
  21821. /**
  21822. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21823. */
  21824. get: function () {
  21825. return this._lightmapMode;
  21826. },
  21827. /**
  21828. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21829. */
  21830. set: function (value) {
  21831. if (this._lightmapMode === value) {
  21832. return;
  21833. }
  21834. this._lightmapMode = value;
  21835. this._markMeshesAsLightDirty();
  21836. },
  21837. enumerable: true,
  21838. configurable: true
  21839. });
  21840. /**
  21841. * Returns the string "Light".
  21842. * @returns the class name
  21843. */
  21844. Light.prototype.getClassName = function () {
  21845. return "Light";
  21846. };
  21847. /**
  21848. * Converts the light information to a readable string for debug purpose.
  21849. * @param fullDetails Supports for multiple levels of logging within scene loading
  21850. * @returns the human readable light info
  21851. */
  21852. Light.prototype.toString = function (fullDetails) {
  21853. var ret = "Name: " + this.name;
  21854. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21855. if (this.animations) {
  21856. for (var i = 0; i < this.animations.length; i++) {
  21857. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21858. }
  21859. }
  21860. if (fullDetails) {
  21861. }
  21862. return ret;
  21863. };
  21864. /**
  21865. * Set the enabled state of this node.
  21866. * @param value - the new enabled state
  21867. */
  21868. Light.prototype.setEnabled = function (value) {
  21869. _super.prototype.setEnabled.call(this, value);
  21870. this._resyncMeshes();
  21871. };
  21872. /**
  21873. * Returns the Light associated shadow generator if any.
  21874. * @return the associated shadow generator.
  21875. */
  21876. Light.prototype.getShadowGenerator = function () {
  21877. return this._shadowGenerator;
  21878. };
  21879. /**
  21880. * Returns a Vector3, the absolute light position in the World.
  21881. * @returns the world space position of the light
  21882. */
  21883. Light.prototype.getAbsolutePosition = function () {
  21884. return BABYLON.Vector3.Zero();
  21885. };
  21886. /**
  21887. * Specifies if the light will affect the passed mesh.
  21888. * @param mesh The mesh to test against the light
  21889. * @return true the mesh is affected otherwise, false.
  21890. */
  21891. Light.prototype.canAffectMesh = function (mesh) {
  21892. if (!mesh) {
  21893. return true;
  21894. }
  21895. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21896. return false;
  21897. }
  21898. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21899. return false;
  21900. }
  21901. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21902. return false;
  21903. }
  21904. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21905. return false;
  21906. }
  21907. return true;
  21908. };
  21909. /**
  21910. * Computes and Returns the light World matrix.
  21911. * @returns the world matrix
  21912. */
  21913. Light.prototype.getWorldMatrix = function () {
  21914. this._currentRenderId = this.getScene().getRenderId();
  21915. this._childRenderId = this._currentRenderId;
  21916. var worldMatrix = this._getWorldMatrix();
  21917. if (this.parent && this.parent.getWorldMatrix) {
  21918. if (!this._parentedWorldMatrix) {
  21919. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21920. }
  21921. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21922. this._markSyncedWithParent();
  21923. return this._parentedWorldMatrix;
  21924. }
  21925. return worldMatrix;
  21926. };
  21927. /**
  21928. * Sort function to order lights for rendering.
  21929. * @param a First Light object to compare to second.
  21930. * @param b Second Light object to compare first.
  21931. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21932. */
  21933. Light.CompareLightsPriority = function (a, b) {
  21934. //shadow-casting lights have priority over non-shadow-casting lights
  21935. //the renderPrioirty is a secondary sort criterion
  21936. if (a.shadowEnabled !== b.shadowEnabled) {
  21937. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21938. }
  21939. return b.renderPriority - a.renderPriority;
  21940. };
  21941. /**
  21942. * Releases resources associated with this node.
  21943. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21944. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21945. */
  21946. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21947. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21948. if (this._shadowGenerator) {
  21949. this._shadowGenerator.dispose();
  21950. this._shadowGenerator = null;
  21951. }
  21952. // Animations
  21953. this.getScene().stopAnimation(this);
  21954. // Remove from meshes
  21955. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21956. var mesh = _a[_i];
  21957. mesh._removeLightSource(this);
  21958. }
  21959. this._uniformBuffer.dispose();
  21960. // Remove from scene
  21961. this.getScene().removeLight(this);
  21962. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21963. };
  21964. /**
  21965. * Returns the light type ID (integer).
  21966. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21967. */
  21968. Light.prototype.getTypeID = function () {
  21969. return 0;
  21970. };
  21971. /**
  21972. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21973. * @returns the scaled intensity in intensity mode unit
  21974. */
  21975. Light.prototype.getScaledIntensity = function () {
  21976. return this._photometricScale * this.intensity;
  21977. };
  21978. /**
  21979. * Returns a new Light object, named "name", from the current one.
  21980. * @param name The name of the cloned light
  21981. * @returns the new created light
  21982. */
  21983. Light.prototype.clone = function (name) {
  21984. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21985. if (!constructor) {
  21986. return null;
  21987. }
  21988. return BABYLON.SerializationHelper.Clone(constructor, this);
  21989. };
  21990. /**
  21991. * Serializes the current light into a Serialization object.
  21992. * @returns the serialized object.
  21993. */
  21994. Light.prototype.serialize = function () {
  21995. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21996. // Type
  21997. serializationObject.type = this.getTypeID();
  21998. // Parent
  21999. if (this.parent) {
  22000. serializationObject.parentId = this.parent.id;
  22001. }
  22002. // Inclusion / exclusions
  22003. if (this.excludedMeshes.length > 0) {
  22004. serializationObject.excludedMeshesIds = [];
  22005. this.excludedMeshes.forEach(function (mesh) {
  22006. serializationObject.excludedMeshesIds.push(mesh.id);
  22007. });
  22008. }
  22009. if (this.includedOnlyMeshes.length > 0) {
  22010. serializationObject.includedOnlyMeshesIds = [];
  22011. this.includedOnlyMeshes.forEach(function (mesh) {
  22012. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22013. });
  22014. }
  22015. // Animations
  22016. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22017. serializationObject.ranges = this.serializeAnimationRanges();
  22018. return serializationObject;
  22019. };
  22020. /**
  22021. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22022. * This new light is named "name" and added to the passed scene.
  22023. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22024. * @param name The friendly name of the light
  22025. * @param scene The scene the new light will belong to
  22026. * @returns the constructor function
  22027. */
  22028. Light.GetConstructorFromName = function (type, name, scene) {
  22029. switch (type) {
  22030. case 0:
  22031. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22032. case 1:
  22033. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22034. case 2:
  22035. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22036. case 3:
  22037. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22038. }
  22039. return null;
  22040. };
  22041. /**
  22042. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22043. * @param parsedLight The JSON representation of the light
  22044. * @param scene The scene to create the parsed light in
  22045. * @returns the created light after parsing
  22046. */
  22047. Light.Parse = function (parsedLight, scene) {
  22048. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22049. if (!constructor) {
  22050. return null;
  22051. }
  22052. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22053. // Inclusion / exclusions
  22054. if (parsedLight.excludedMeshesIds) {
  22055. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22056. }
  22057. if (parsedLight.includedOnlyMeshesIds) {
  22058. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22059. }
  22060. // Parent
  22061. if (parsedLight.parentId) {
  22062. light._waitingParentId = parsedLight.parentId;
  22063. }
  22064. // Animations
  22065. if (parsedLight.animations) {
  22066. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22067. var parsedAnimation = parsedLight.animations[animationIndex];
  22068. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22069. }
  22070. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22071. }
  22072. if (parsedLight.autoAnimate) {
  22073. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22074. }
  22075. return light;
  22076. };
  22077. Light.prototype._hookArrayForExcluded = function (array) {
  22078. var _this = this;
  22079. var oldPush = array.push;
  22080. array.push = function () {
  22081. var items = [];
  22082. for (var _i = 0; _i < arguments.length; _i++) {
  22083. items[_i] = arguments[_i];
  22084. }
  22085. var result = oldPush.apply(array, items);
  22086. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22087. var item = items_1[_a];
  22088. item._resyncLighSource(_this);
  22089. }
  22090. return result;
  22091. };
  22092. var oldSplice = array.splice;
  22093. array.splice = function (index, deleteCount) {
  22094. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22095. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22096. var item = deleted_1[_i];
  22097. item._resyncLighSource(_this);
  22098. }
  22099. return deleted;
  22100. };
  22101. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22102. var item = array_1[_i];
  22103. item._resyncLighSource(this);
  22104. }
  22105. };
  22106. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22107. var _this = this;
  22108. var oldPush = array.push;
  22109. array.push = function () {
  22110. var items = [];
  22111. for (var _i = 0; _i < arguments.length; _i++) {
  22112. items[_i] = arguments[_i];
  22113. }
  22114. var result = oldPush.apply(array, items);
  22115. _this._resyncMeshes();
  22116. return result;
  22117. };
  22118. var oldSplice = array.splice;
  22119. array.splice = function (index, deleteCount) {
  22120. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22121. _this._resyncMeshes();
  22122. return deleted;
  22123. };
  22124. this._resyncMeshes();
  22125. };
  22126. Light.prototype._resyncMeshes = function () {
  22127. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22128. var mesh = _a[_i];
  22129. mesh._resyncLighSource(this);
  22130. }
  22131. };
  22132. /**
  22133. * Forces the meshes to update their light related information in their rendering used effects
  22134. * @hidden Internal Use Only
  22135. */
  22136. Light.prototype._markMeshesAsLightDirty = function () {
  22137. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22138. var mesh = _a[_i];
  22139. if (mesh._lightSources.indexOf(this) !== -1) {
  22140. mesh._markSubMeshesAsLightDirty();
  22141. }
  22142. }
  22143. };
  22144. /**
  22145. * Recomputes the cached photometric scale if needed.
  22146. */
  22147. Light.prototype._computePhotometricScale = function () {
  22148. this._photometricScale = this._getPhotometricScale();
  22149. this.getScene().resetCachedMaterial();
  22150. };
  22151. /**
  22152. * Returns the Photometric Scale according to the light type and intensity mode.
  22153. */
  22154. Light.prototype._getPhotometricScale = function () {
  22155. var photometricScale = 0.0;
  22156. var lightTypeID = this.getTypeID();
  22157. //get photometric mode
  22158. var photometricMode = this.intensityMode;
  22159. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22160. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22161. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22162. }
  22163. else {
  22164. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22165. }
  22166. }
  22167. //compute photometric scale
  22168. switch (lightTypeID) {
  22169. case Light.LIGHTTYPEID_POINTLIGHT:
  22170. case Light.LIGHTTYPEID_SPOTLIGHT:
  22171. switch (photometricMode) {
  22172. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22173. photometricScale = 1.0 / (4.0 * Math.PI);
  22174. break;
  22175. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22176. photometricScale = 1.0;
  22177. break;
  22178. case Light.INTENSITYMODE_LUMINANCE:
  22179. photometricScale = this.radius * this.radius;
  22180. break;
  22181. }
  22182. break;
  22183. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22184. switch (photometricMode) {
  22185. case Light.INTENSITYMODE_ILLUMINANCE:
  22186. photometricScale = 1.0;
  22187. break;
  22188. case Light.INTENSITYMODE_LUMINANCE:
  22189. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22190. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22191. var apexAngleRadians = this.radius;
  22192. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22193. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22194. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22195. photometricScale = solidAngle;
  22196. break;
  22197. }
  22198. break;
  22199. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22200. // No fall off in hemisperic light.
  22201. photometricScale = 1.0;
  22202. break;
  22203. }
  22204. return photometricScale;
  22205. };
  22206. /**
  22207. * Reorder the light in the scene according to their defined priority.
  22208. * @hidden Internal Use Only
  22209. */
  22210. Light.prototype._reorderLightsInScene = function () {
  22211. var scene = this.getScene();
  22212. if (this._renderPriority != 0) {
  22213. scene.requireLightSorting = true;
  22214. }
  22215. this.getScene().sortLightsByPriority();
  22216. };
  22217. //lightmapMode Consts
  22218. Light._LIGHTMAP_DEFAULT = 0;
  22219. Light._LIGHTMAP_SPECULAR = 1;
  22220. Light._LIGHTMAP_SHADOWSONLY = 2;
  22221. // Intensity Mode Consts
  22222. Light._INTENSITYMODE_AUTOMATIC = 0;
  22223. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22224. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22225. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22226. Light._INTENSITYMODE_LUMINANCE = 4;
  22227. // Light types ids const.
  22228. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22229. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22230. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22231. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22232. __decorate([
  22233. BABYLON.serializeAsColor3()
  22234. ], Light.prototype, "diffuse", void 0);
  22235. __decorate([
  22236. BABYLON.serializeAsColor3()
  22237. ], Light.prototype, "specular", void 0);
  22238. __decorate([
  22239. BABYLON.serialize()
  22240. ], Light.prototype, "intensity", void 0);
  22241. __decorate([
  22242. BABYLON.serialize()
  22243. ], Light.prototype, "range", void 0);
  22244. __decorate([
  22245. BABYLON.serialize()
  22246. ], Light.prototype, "intensityMode", null);
  22247. __decorate([
  22248. BABYLON.serialize()
  22249. ], Light.prototype, "radius", null);
  22250. __decorate([
  22251. BABYLON.serialize()
  22252. ], Light.prototype, "_renderPriority", void 0);
  22253. __decorate([
  22254. BABYLON.expandToProperty("_reorderLightsInScene")
  22255. ], Light.prototype, "renderPriority", void 0);
  22256. __decorate([
  22257. BABYLON.serialize("shadowEnabled")
  22258. ], Light.prototype, "_shadowEnabled", void 0);
  22259. __decorate([
  22260. BABYLON.serialize("excludeWithLayerMask")
  22261. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22262. __decorate([
  22263. BABYLON.serialize("includeOnlyWithLayerMask")
  22264. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22265. __decorate([
  22266. BABYLON.serialize("lightmapMode")
  22267. ], Light.prototype, "_lightmapMode", void 0);
  22268. return Light;
  22269. }(BABYLON.Node));
  22270. BABYLON.Light = Light;
  22271. })(BABYLON || (BABYLON = {}));
  22272. //# sourceMappingURL=babylon.light.js.map
  22273. var BABYLON;
  22274. (function (BABYLON) {
  22275. var Camera = /** @class */ (function (_super) {
  22276. __extends(Camera, _super);
  22277. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22278. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22279. var _this = _super.call(this, name, scene) || this;
  22280. /**
  22281. * The vector the camera should consider as up.
  22282. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22283. */
  22284. _this.upVector = BABYLON.Vector3.Up();
  22285. _this.orthoLeft = null;
  22286. _this.orthoRight = null;
  22287. _this.orthoBottom = null;
  22288. _this.orthoTop = null;
  22289. /**
  22290. * FOV is set in Radians. (default is 0.8)
  22291. */
  22292. _this.fov = 0.8;
  22293. _this.minZ = 1;
  22294. _this.maxZ = 10000.0;
  22295. _this.inertia = 0.9;
  22296. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22297. _this.isIntermediate = false;
  22298. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22299. /**
  22300. * Restricts the camera to viewing objects with the same layerMask.
  22301. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22302. */
  22303. _this.layerMask = 0x0FFFFFFF;
  22304. /**
  22305. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22306. */
  22307. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22308. // Camera rig members
  22309. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22310. _this._rigCameras = new Array();
  22311. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22312. _this._skipRendering = false;
  22313. _this.customRenderTargets = new Array();
  22314. // Observables
  22315. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22316. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22317. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22318. _this.onRestoreStateObservable = new BABYLON.Observable();
  22319. // Cache
  22320. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22321. _this._projectionMatrix = new BABYLON.Matrix();
  22322. _this._doNotComputeProjectionMatrix = false;
  22323. _this._worldMatrix = BABYLON.Matrix.Identity();
  22324. _this._postProcesses = new Array();
  22325. _this._transformMatrix = BABYLON.Matrix.Zero();
  22326. _this._activeMeshes = new BABYLON.SmartArray(256);
  22327. _this._globalPosition = BABYLON.Vector3.Zero();
  22328. _this._refreshFrustumPlanes = true;
  22329. _this.getScene().addCamera(_this);
  22330. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22331. _this.getScene().activeCamera = _this;
  22332. }
  22333. _this.position = position;
  22334. return _this;
  22335. }
  22336. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22337. get: function () {
  22338. return Camera._PERSPECTIVE_CAMERA;
  22339. },
  22340. enumerable: true,
  22341. configurable: true
  22342. });
  22343. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22344. get: function () {
  22345. return Camera._ORTHOGRAPHIC_CAMERA;
  22346. },
  22347. enumerable: true,
  22348. configurable: true
  22349. });
  22350. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22351. /**
  22352. * This is the default FOV mode for perspective cameras.
  22353. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22354. *
  22355. */
  22356. get: function () {
  22357. return Camera._FOVMODE_VERTICAL_FIXED;
  22358. },
  22359. enumerable: true,
  22360. configurable: true
  22361. });
  22362. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22363. /**
  22364. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22365. *
  22366. */
  22367. get: function () {
  22368. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22369. },
  22370. enumerable: true,
  22371. configurable: true
  22372. });
  22373. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22374. get: function () {
  22375. return Camera._RIG_MODE_NONE;
  22376. },
  22377. enumerable: true,
  22378. configurable: true
  22379. });
  22380. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22381. get: function () {
  22382. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22383. },
  22384. enumerable: true,
  22385. configurable: true
  22386. });
  22387. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22388. get: function () {
  22389. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22390. },
  22391. enumerable: true,
  22392. configurable: true
  22393. });
  22394. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22395. get: function () {
  22396. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22397. },
  22398. enumerable: true,
  22399. configurable: true
  22400. });
  22401. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22402. get: function () {
  22403. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22404. },
  22405. enumerable: true,
  22406. configurable: true
  22407. });
  22408. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22409. get: function () {
  22410. return Camera._RIG_MODE_VR;
  22411. },
  22412. enumerable: true,
  22413. configurable: true
  22414. });
  22415. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22416. get: function () {
  22417. return Camera._RIG_MODE_WEBVR;
  22418. },
  22419. enumerable: true,
  22420. configurable: true
  22421. });
  22422. /**
  22423. * Store current camera state (fov, position, etc..)
  22424. */
  22425. Camera.prototype.storeState = function () {
  22426. this._stateStored = true;
  22427. this._storedFov = this.fov;
  22428. return this;
  22429. };
  22430. /**
  22431. * Restores the camera state values if it has been stored. You must call storeState() first
  22432. */
  22433. Camera.prototype._restoreStateValues = function () {
  22434. if (!this._stateStored) {
  22435. return false;
  22436. }
  22437. this.fov = this._storedFov;
  22438. return true;
  22439. };
  22440. /**
  22441. * Restored camera state. You must call storeState() first
  22442. */
  22443. Camera.prototype.restoreState = function () {
  22444. if (this._restoreStateValues()) {
  22445. this.onRestoreStateObservable.notifyObservers(this);
  22446. return true;
  22447. }
  22448. return false;
  22449. };
  22450. Camera.prototype.getClassName = function () {
  22451. return "Camera";
  22452. };
  22453. /**
  22454. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22455. */
  22456. Camera.prototype.toString = function (fullDetails) {
  22457. var ret = "Name: " + this.name;
  22458. ret += ", type: " + this.getClassName();
  22459. if (this.animations) {
  22460. for (var i = 0; i < this.animations.length; i++) {
  22461. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22462. }
  22463. }
  22464. if (fullDetails) {
  22465. }
  22466. return ret;
  22467. };
  22468. Object.defineProperty(Camera.prototype, "globalPosition", {
  22469. get: function () {
  22470. return this._globalPosition;
  22471. },
  22472. enumerable: true,
  22473. configurable: true
  22474. });
  22475. Camera.prototype.getActiveMeshes = function () {
  22476. return this._activeMeshes;
  22477. };
  22478. Camera.prototype.isActiveMesh = function (mesh) {
  22479. return (this._activeMeshes.indexOf(mesh) !== -1);
  22480. };
  22481. /**
  22482. * Is this camera ready to be used/rendered
  22483. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22484. * @return true if the camera is ready
  22485. */
  22486. Camera.prototype.isReady = function (completeCheck) {
  22487. if (completeCheck === void 0) { completeCheck = false; }
  22488. if (completeCheck) {
  22489. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22490. var pp = _a[_i];
  22491. if (pp && !pp.isReady()) {
  22492. return false;
  22493. }
  22494. }
  22495. }
  22496. return _super.prototype.isReady.call(this, completeCheck);
  22497. };
  22498. //Cache
  22499. Camera.prototype._initCache = function () {
  22500. _super.prototype._initCache.call(this);
  22501. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22502. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22503. this._cache.mode = undefined;
  22504. this._cache.minZ = undefined;
  22505. this._cache.maxZ = undefined;
  22506. this._cache.fov = undefined;
  22507. this._cache.fovMode = undefined;
  22508. this._cache.aspectRatio = undefined;
  22509. this._cache.orthoLeft = undefined;
  22510. this._cache.orthoRight = undefined;
  22511. this._cache.orthoBottom = undefined;
  22512. this._cache.orthoTop = undefined;
  22513. this._cache.renderWidth = undefined;
  22514. this._cache.renderHeight = undefined;
  22515. };
  22516. Camera.prototype._updateCache = function (ignoreParentClass) {
  22517. if (!ignoreParentClass) {
  22518. _super.prototype._updateCache.call(this);
  22519. }
  22520. this._cache.position.copyFrom(this.position);
  22521. this._cache.upVector.copyFrom(this.upVector);
  22522. };
  22523. // Synchronized
  22524. Camera.prototype._isSynchronized = function () {
  22525. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22526. };
  22527. Camera.prototype._isSynchronizedViewMatrix = function () {
  22528. if (!_super.prototype._isSynchronized.call(this))
  22529. return false;
  22530. return this._cache.position.equals(this.position)
  22531. && this._cache.upVector.equals(this.upVector)
  22532. && this.isSynchronizedWithParent();
  22533. };
  22534. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22535. var check = this._cache.mode === this.mode
  22536. && this._cache.minZ === this.minZ
  22537. && this._cache.maxZ === this.maxZ;
  22538. if (!check) {
  22539. return false;
  22540. }
  22541. var engine = this.getEngine();
  22542. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22543. check = this._cache.fov === this.fov
  22544. && this._cache.fovMode === this.fovMode
  22545. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22546. }
  22547. else {
  22548. check = this._cache.orthoLeft === this.orthoLeft
  22549. && this._cache.orthoRight === this.orthoRight
  22550. && this._cache.orthoBottom === this.orthoBottom
  22551. && this._cache.orthoTop === this.orthoTop
  22552. && this._cache.renderWidth === engine.getRenderWidth()
  22553. && this._cache.renderHeight === engine.getRenderHeight();
  22554. }
  22555. return check;
  22556. };
  22557. // Controls
  22558. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22559. };
  22560. Camera.prototype.detachControl = function (element) {
  22561. };
  22562. Camera.prototype.update = function () {
  22563. this._checkInputs();
  22564. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22565. this._updateRigCameras();
  22566. }
  22567. };
  22568. Camera.prototype._checkInputs = function () {
  22569. this.onAfterCheckInputsObservable.notifyObservers(this);
  22570. };
  22571. Object.defineProperty(Camera.prototype, "rigCameras", {
  22572. get: function () {
  22573. return this._rigCameras;
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22579. get: function () {
  22580. return this._rigPostProcess;
  22581. },
  22582. enumerable: true,
  22583. configurable: true
  22584. });
  22585. /**
  22586. * Internal, gets the first post proces.
  22587. * @returns the first post process to be run on this camera.
  22588. */
  22589. Camera.prototype._getFirstPostProcess = function () {
  22590. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22591. if (this._postProcesses[ppIndex] !== null) {
  22592. return this._postProcesses[ppIndex];
  22593. }
  22594. }
  22595. return null;
  22596. };
  22597. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22598. // invalidate framebuffer
  22599. var firstPostProcess = this._getFirstPostProcess();
  22600. if (firstPostProcess) {
  22601. firstPostProcess.markTextureDirty();
  22602. }
  22603. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22604. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22605. var cam = this._rigCameras[i];
  22606. var rigPostProcess = cam._rigPostProcess;
  22607. // for VR rig, there does not have to be a post process
  22608. if (rigPostProcess) {
  22609. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22610. if (isPass) {
  22611. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22612. cam.isIntermediate = this._postProcesses.length === 0;
  22613. }
  22614. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22615. rigPostProcess.markTextureDirty();
  22616. }
  22617. else {
  22618. cam._postProcesses = this._postProcesses.slice(0);
  22619. }
  22620. }
  22621. };
  22622. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22623. if (insertAt === void 0) { insertAt = null; }
  22624. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22625. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22626. return 0;
  22627. }
  22628. if (insertAt == null || insertAt < 0) {
  22629. this._postProcesses.push(postProcess);
  22630. }
  22631. else if (this._postProcesses[insertAt] === null) {
  22632. this._postProcesses[insertAt] = postProcess;
  22633. }
  22634. else {
  22635. this._postProcesses.splice(insertAt, 0, postProcess);
  22636. }
  22637. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22638. return this._postProcesses.indexOf(postProcess);
  22639. };
  22640. Camera.prototype.detachPostProcess = function (postProcess) {
  22641. var idx = this._postProcesses.indexOf(postProcess);
  22642. if (idx !== -1) {
  22643. this._postProcesses[idx] = null;
  22644. }
  22645. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22646. };
  22647. Camera.prototype.getWorldMatrix = function () {
  22648. if (this._isSynchronizedViewMatrix()) {
  22649. return this._worldMatrix;
  22650. }
  22651. // Getting the the view matrix will also compute the world matrix.
  22652. this.getViewMatrix();
  22653. return this._worldMatrix;
  22654. };
  22655. Camera.prototype._getViewMatrix = function () {
  22656. return BABYLON.Matrix.Identity();
  22657. };
  22658. Camera.prototype.getViewMatrix = function (force) {
  22659. if (!force && this._isSynchronizedViewMatrix()) {
  22660. return this._computedViewMatrix;
  22661. }
  22662. this.updateCache();
  22663. this._computedViewMatrix = this._getViewMatrix();
  22664. this._currentRenderId = this.getScene().getRenderId();
  22665. this._childRenderId = this._currentRenderId;
  22666. this._refreshFrustumPlanes = true;
  22667. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22668. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22669. }
  22670. this.onViewMatrixChangedObservable.notifyObservers(this);
  22671. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22672. return this._computedViewMatrix;
  22673. };
  22674. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22675. this._doNotComputeProjectionMatrix = true;
  22676. if (projection !== undefined) {
  22677. this._projectionMatrix = projection;
  22678. }
  22679. };
  22680. ;
  22681. Camera.prototype.unfreezeProjectionMatrix = function () {
  22682. this._doNotComputeProjectionMatrix = false;
  22683. };
  22684. ;
  22685. Camera.prototype.getProjectionMatrix = function (force) {
  22686. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22687. return this._projectionMatrix;
  22688. }
  22689. // Cache
  22690. this._cache.mode = this.mode;
  22691. this._cache.minZ = this.minZ;
  22692. this._cache.maxZ = this.maxZ;
  22693. // Matrix
  22694. this._refreshFrustumPlanes = true;
  22695. var engine = this.getEngine();
  22696. var scene = this.getScene();
  22697. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22698. this._cache.fov = this.fov;
  22699. this._cache.fovMode = this.fovMode;
  22700. this._cache.aspectRatio = engine.getAspectRatio(this);
  22701. if (this.minZ <= 0) {
  22702. this.minZ = 0.1;
  22703. }
  22704. if (scene.useRightHandedSystem) {
  22705. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22706. }
  22707. else {
  22708. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22709. }
  22710. }
  22711. else {
  22712. var halfWidth = engine.getRenderWidth() / 2.0;
  22713. var halfHeight = engine.getRenderHeight() / 2.0;
  22714. if (scene.useRightHandedSystem) {
  22715. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22716. }
  22717. else {
  22718. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22719. }
  22720. this._cache.orthoLeft = this.orthoLeft;
  22721. this._cache.orthoRight = this.orthoRight;
  22722. this._cache.orthoBottom = this.orthoBottom;
  22723. this._cache.orthoTop = this.orthoTop;
  22724. this._cache.renderWidth = engine.getRenderWidth();
  22725. this._cache.renderHeight = engine.getRenderHeight();
  22726. }
  22727. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22728. return this._projectionMatrix;
  22729. };
  22730. Camera.prototype.getTranformationMatrix = function () {
  22731. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22732. return this._transformMatrix;
  22733. };
  22734. Camera.prototype.updateFrustumPlanes = function () {
  22735. if (!this._refreshFrustumPlanes) {
  22736. return;
  22737. }
  22738. this.getTranformationMatrix();
  22739. if (!this._frustumPlanes) {
  22740. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22741. }
  22742. else {
  22743. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22744. }
  22745. this._refreshFrustumPlanes = false;
  22746. };
  22747. Camera.prototype.isInFrustum = function (target) {
  22748. this.updateFrustumPlanes();
  22749. return target.isInFrustum(this._frustumPlanes);
  22750. };
  22751. Camera.prototype.isCompletelyInFrustum = function (target) {
  22752. this.updateFrustumPlanes();
  22753. return target.isCompletelyInFrustum(this._frustumPlanes);
  22754. };
  22755. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22756. if (length === void 0) { length = 100; }
  22757. if (!transform) {
  22758. transform = this.getWorldMatrix();
  22759. }
  22760. if (!origin) {
  22761. origin = this.position;
  22762. }
  22763. var forward = new BABYLON.Vector3(0, 0, 1);
  22764. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22765. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22766. return new BABYLON.Ray(origin, direction, length);
  22767. };
  22768. /**
  22769. * Releases resources associated with this node.
  22770. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22771. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22772. */
  22773. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22774. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22775. // Observables
  22776. this.onViewMatrixChangedObservable.clear();
  22777. this.onProjectionMatrixChangedObservable.clear();
  22778. this.onAfterCheckInputsObservable.clear();
  22779. this.onRestoreStateObservable.clear();
  22780. // Inputs
  22781. if (this.inputs) {
  22782. this.inputs.clear();
  22783. }
  22784. // Animations
  22785. this.getScene().stopAnimation(this);
  22786. // Remove from scene
  22787. this.getScene().removeCamera(this);
  22788. while (this._rigCameras.length > 0) {
  22789. var camera = this._rigCameras.pop();
  22790. if (camera) {
  22791. camera.dispose();
  22792. }
  22793. }
  22794. // Postprocesses
  22795. if (this._rigPostProcess) {
  22796. this._rigPostProcess.dispose(this);
  22797. this._rigPostProcess = null;
  22798. this._postProcesses = [];
  22799. }
  22800. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22801. this._rigPostProcess = null;
  22802. this._postProcesses = [];
  22803. }
  22804. else {
  22805. var i = this._postProcesses.length;
  22806. while (--i >= 0) {
  22807. var postProcess = this._postProcesses[i];
  22808. if (postProcess) {
  22809. postProcess.dispose(this);
  22810. }
  22811. }
  22812. }
  22813. // Render targets
  22814. var i = this.customRenderTargets.length;
  22815. while (--i >= 0) {
  22816. this.customRenderTargets[i].dispose();
  22817. }
  22818. this.customRenderTargets = [];
  22819. // Active Meshes
  22820. this._activeMeshes.dispose();
  22821. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22822. };
  22823. Object.defineProperty(Camera.prototype, "leftCamera", {
  22824. // ---- Camera rigs section ----
  22825. get: function () {
  22826. if (this._rigCameras.length < 1) {
  22827. return null;
  22828. }
  22829. return this._rigCameras[0];
  22830. },
  22831. enumerable: true,
  22832. configurable: true
  22833. });
  22834. Object.defineProperty(Camera.prototype, "rightCamera", {
  22835. get: function () {
  22836. if (this._rigCameras.length < 2) {
  22837. return null;
  22838. }
  22839. return this._rigCameras[1];
  22840. },
  22841. enumerable: true,
  22842. configurable: true
  22843. });
  22844. Camera.prototype.getLeftTarget = function () {
  22845. if (this._rigCameras.length < 1) {
  22846. return null;
  22847. }
  22848. return this._rigCameras[0].getTarget();
  22849. };
  22850. Camera.prototype.getRightTarget = function () {
  22851. if (this._rigCameras.length < 2) {
  22852. return null;
  22853. }
  22854. return this._rigCameras[1].getTarget();
  22855. };
  22856. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22857. if (this.cameraRigMode === mode) {
  22858. return;
  22859. }
  22860. while (this._rigCameras.length > 0) {
  22861. var camera = this._rigCameras.pop();
  22862. if (camera) {
  22863. camera.dispose();
  22864. }
  22865. }
  22866. this.cameraRigMode = mode;
  22867. this._cameraRigParams = {};
  22868. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22869. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22870. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22871. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22872. // create the rig cameras, unless none
  22873. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22874. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22875. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22876. if (leftCamera && rightCamera) {
  22877. this._rigCameras.push(leftCamera);
  22878. this._rigCameras.push(rightCamera);
  22879. }
  22880. }
  22881. switch (this.cameraRigMode) {
  22882. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22883. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22884. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22885. break;
  22886. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22887. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22888. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22889. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22890. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22891. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22892. break;
  22893. case Camera.RIG_MODE_VR:
  22894. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22895. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22896. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22897. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22898. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22899. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22900. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22901. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22902. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22903. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22904. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22905. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22906. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22907. if (metrics.compensateDistortion) {
  22908. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22909. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22910. }
  22911. break;
  22912. case Camera.RIG_MODE_WEBVR:
  22913. if (rigParams.vrDisplay) {
  22914. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22915. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22916. //Left eye
  22917. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22918. this._rigCameras[0].setCameraRigParameter("left", true);
  22919. //leaving this for future reference
  22920. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22921. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22922. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22923. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22924. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22925. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22926. this._rigCameras[0].parent = this;
  22927. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22928. //Right eye
  22929. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22930. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22931. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22932. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22933. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22934. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22935. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22936. this._rigCameras[1].parent = this;
  22937. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22938. if (Camera.UseAlternateWebVRRendering) {
  22939. this._rigCameras[1]._skipRendering = true;
  22940. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22941. }
  22942. }
  22943. break;
  22944. }
  22945. this._cascadePostProcessesToRigCams();
  22946. this.update();
  22947. };
  22948. Camera.prototype._getVRProjectionMatrix = function () {
  22949. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22950. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22951. return this._projectionMatrix;
  22952. };
  22953. Camera.prototype._updateCameraRotationMatrix = function () {
  22954. //Here for WebVR
  22955. };
  22956. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22957. //Here for WebVR
  22958. };
  22959. /**
  22960. * This function MUST be overwritten by the different WebVR cameras available.
  22961. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22962. */
  22963. Camera.prototype._getWebVRProjectionMatrix = function () {
  22964. return BABYLON.Matrix.Identity();
  22965. };
  22966. /**
  22967. * This function MUST be overwritten by the different WebVR cameras available.
  22968. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22969. */
  22970. Camera.prototype._getWebVRViewMatrix = function () {
  22971. return BABYLON.Matrix.Identity();
  22972. };
  22973. Camera.prototype.setCameraRigParameter = function (name, value) {
  22974. if (!this._cameraRigParams) {
  22975. this._cameraRigParams = {};
  22976. }
  22977. this._cameraRigParams[name] = value;
  22978. //provisionnally:
  22979. if (name === "interaxialDistance") {
  22980. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22981. }
  22982. };
  22983. /**
  22984. * needs to be overridden by children so sub has required properties to be copied
  22985. */
  22986. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22987. return null;
  22988. };
  22989. /**
  22990. * May need to be overridden by children
  22991. */
  22992. Camera.prototype._updateRigCameras = function () {
  22993. for (var i = 0; i < this._rigCameras.length; i++) {
  22994. this._rigCameras[i].minZ = this.minZ;
  22995. this._rigCameras[i].maxZ = this.maxZ;
  22996. this._rigCameras[i].fov = this.fov;
  22997. }
  22998. // only update viewport when ANAGLYPH
  22999. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23000. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23001. }
  23002. };
  23003. Camera.prototype._setupInputs = function () {
  23004. };
  23005. Camera.prototype.serialize = function () {
  23006. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23007. // Type
  23008. serializationObject.type = this.getClassName();
  23009. // Parent
  23010. if (this.parent) {
  23011. serializationObject.parentId = this.parent.id;
  23012. }
  23013. if (this.inputs) {
  23014. this.inputs.serialize(serializationObject);
  23015. }
  23016. // Animations
  23017. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23018. serializationObject.ranges = this.serializeAnimationRanges();
  23019. return serializationObject;
  23020. };
  23021. Camera.prototype.clone = function (name) {
  23022. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23023. };
  23024. Camera.prototype.getDirection = function (localAxis) {
  23025. var result = BABYLON.Vector3.Zero();
  23026. this.getDirectionToRef(localAxis, result);
  23027. return result;
  23028. };
  23029. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23030. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23031. };
  23032. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23033. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23034. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23035. switch (type) {
  23036. case "ArcRotateCamera":
  23037. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23038. case "DeviceOrientationCamera":
  23039. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23040. case "FollowCamera":
  23041. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23042. case "ArcFollowCamera":
  23043. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23044. case "GamepadCamera":
  23045. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23046. case "TouchCamera":
  23047. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23048. case "VirtualJoysticksCamera":
  23049. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23050. case "WebVRFreeCamera":
  23051. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23052. case "WebVRGamepadCamera":
  23053. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23054. case "VRDeviceOrientationFreeCamera":
  23055. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23056. case "VRDeviceOrientationGamepadCamera":
  23057. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23058. case "AnaglyphArcRotateCamera":
  23059. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23060. case "AnaglyphFreeCamera":
  23061. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23062. case "AnaglyphGamepadCamera":
  23063. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23064. case "AnaglyphUniversalCamera":
  23065. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23066. case "StereoscopicArcRotateCamera":
  23067. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23068. case "StereoscopicFreeCamera":
  23069. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23070. case "StereoscopicGamepadCamera":
  23071. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23072. case "StereoscopicUniversalCamera":
  23073. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23074. case "FreeCamera": // Forcing Universal here
  23075. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23076. default: // Universal Camera is the default value
  23077. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23078. }
  23079. };
  23080. Camera.prototype.computeWorldMatrix = function () {
  23081. return this.getWorldMatrix();
  23082. };
  23083. Camera.Parse = function (parsedCamera, scene) {
  23084. var type = parsedCamera.type;
  23085. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23086. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23087. // Parent
  23088. if (parsedCamera.parentId) {
  23089. camera._waitingParentId = parsedCamera.parentId;
  23090. }
  23091. //If camera has an input manager, let it parse inputs settings
  23092. if (camera.inputs) {
  23093. camera.inputs.parse(parsedCamera);
  23094. camera._setupInputs();
  23095. }
  23096. if (camera.setPosition) { // need to force position
  23097. camera.position.copyFromFloats(0, 0, 0);
  23098. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23099. }
  23100. // Target
  23101. if (parsedCamera.target) {
  23102. if (camera.setTarget) {
  23103. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23104. }
  23105. }
  23106. // Apply 3d rig, when found
  23107. if (parsedCamera.cameraRigMode) {
  23108. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23109. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23110. }
  23111. // Animations
  23112. if (parsedCamera.animations) {
  23113. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23114. var parsedAnimation = parsedCamera.animations[animationIndex];
  23115. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23116. }
  23117. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23118. }
  23119. if (parsedCamera.autoAnimate) {
  23120. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23121. }
  23122. return camera;
  23123. };
  23124. // Statics
  23125. Camera._PERSPECTIVE_CAMERA = 0;
  23126. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23127. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23128. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23129. Camera._RIG_MODE_NONE = 0;
  23130. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23131. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23132. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23133. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23134. Camera._RIG_MODE_VR = 20;
  23135. Camera._RIG_MODE_WEBVR = 21;
  23136. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23137. Camera.UseAlternateWebVRRendering = false;
  23138. __decorate([
  23139. BABYLON.serializeAsVector3()
  23140. ], Camera.prototype, "position", void 0);
  23141. __decorate([
  23142. BABYLON.serializeAsVector3()
  23143. ], Camera.prototype, "upVector", void 0);
  23144. __decorate([
  23145. BABYLON.serialize()
  23146. ], Camera.prototype, "orthoLeft", void 0);
  23147. __decorate([
  23148. BABYLON.serialize()
  23149. ], Camera.prototype, "orthoRight", void 0);
  23150. __decorate([
  23151. BABYLON.serialize()
  23152. ], Camera.prototype, "orthoBottom", void 0);
  23153. __decorate([
  23154. BABYLON.serialize()
  23155. ], Camera.prototype, "orthoTop", void 0);
  23156. __decorate([
  23157. BABYLON.serialize()
  23158. ], Camera.prototype, "fov", void 0);
  23159. __decorate([
  23160. BABYLON.serialize()
  23161. ], Camera.prototype, "minZ", void 0);
  23162. __decorate([
  23163. BABYLON.serialize()
  23164. ], Camera.prototype, "maxZ", void 0);
  23165. __decorate([
  23166. BABYLON.serialize()
  23167. ], Camera.prototype, "inertia", void 0);
  23168. __decorate([
  23169. BABYLON.serialize()
  23170. ], Camera.prototype, "mode", void 0);
  23171. __decorate([
  23172. BABYLON.serialize()
  23173. ], Camera.prototype, "layerMask", void 0);
  23174. __decorate([
  23175. BABYLON.serialize()
  23176. ], Camera.prototype, "fovMode", void 0);
  23177. __decorate([
  23178. BABYLON.serialize()
  23179. ], Camera.prototype, "cameraRigMode", void 0);
  23180. __decorate([
  23181. BABYLON.serialize()
  23182. ], Camera.prototype, "interaxialDistance", void 0);
  23183. __decorate([
  23184. BABYLON.serialize()
  23185. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23186. return Camera;
  23187. }(BABYLON.Node));
  23188. BABYLON.Camera = Camera;
  23189. })(BABYLON || (BABYLON = {}));
  23190. //# sourceMappingURL=babylon.camera.js.map
  23191. var BABYLON;
  23192. (function (BABYLON) {
  23193. var RenderingManager = /** @class */ (function () {
  23194. function RenderingManager(scene) {
  23195. this._renderingGroups = new Array();
  23196. this._autoClearDepthStencil = {};
  23197. this._customOpaqueSortCompareFn = {};
  23198. this._customAlphaTestSortCompareFn = {};
  23199. this._customTransparentSortCompareFn = {};
  23200. this._renderinGroupInfo = null;
  23201. this._scene = scene;
  23202. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23203. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23204. }
  23205. }
  23206. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23207. if (depth === void 0) { depth = true; }
  23208. if (stencil === void 0) { stencil = true; }
  23209. if (this._depthStencilBufferAlreadyCleaned) {
  23210. return;
  23211. }
  23212. this._scene.getEngine().clear(null, false, depth, stencil);
  23213. this._depthStencilBufferAlreadyCleaned = true;
  23214. };
  23215. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23216. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23217. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23218. var info = null;
  23219. if (observable) {
  23220. if (!this._renderinGroupInfo) {
  23221. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23222. }
  23223. info = this._renderinGroupInfo;
  23224. info.scene = this._scene;
  23225. info.camera = this._scene.activeCamera;
  23226. }
  23227. // Dispatch sprites
  23228. if (renderSprites) {
  23229. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23230. var manager = this._scene.spriteManagers[index];
  23231. this.dispatchSprites(manager);
  23232. }
  23233. }
  23234. // Render
  23235. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23236. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23237. var renderingGroup = this._renderingGroups[index];
  23238. if (!renderingGroup && !observable)
  23239. continue;
  23240. var renderingGroupMask = 0;
  23241. // Fire PRECLEAR stage
  23242. if (observable && info) {
  23243. renderingGroupMask = Math.pow(2, index);
  23244. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23245. info.renderingGroupId = index;
  23246. observable.notifyObservers(info, renderingGroupMask);
  23247. }
  23248. // Clear depth/stencil if needed
  23249. if (RenderingManager.AUTOCLEAR) {
  23250. var autoClear = this._autoClearDepthStencil[index];
  23251. if (autoClear && autoClear.autoClear) {
  23252. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23253. }
  23254. }
  23255. if (observable && info) {
  23256. // Fire PREOPAQUE stage
  23257. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23258. observable.notifyObservers(info, renderingGroupMask);
  23259. // Fire PRETRANSPARENT stage
  23260. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23261. observable.notifyObservers(info, renderingGroupMask);
  23262. }
  23263. if (renderingGroup)
  23264. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23265. // Fire POSTTRANSPARENT stage
  23266. if (observable && info) {
  23267. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23268. observable.notifyObservers(info, renderingGroupMask);
  23269. }
  23270. }
  23271. };
  23272. RenderingManager.prototype.reset = function () {
  23273. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23274. var renderingGroup = this._renderingGroups[index];
  23275. if (renderingGroup) {
  23276. renderingGroup.prepare();
  23277. }
  23278. }
  23279. };
  23280. RenderingManager.prototype.dispose = function () {
  23281. this.freeRenderingGroups();
  23282. this._renderingGroups.length = 0;
  23283. };
  23284. /**
  23285. * Clear the info related to rendering groups preventing retention points during dispose.
  23286. */
  23287. RenderingManager.prototype.freeRenderingGroups = function () {
  23288. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23289. var renderingGroup = this._renderingGroups[index];
  23290. if (renderingGroup) {
  23291. renderingGroup.dispose();
  23292. }
  23293. }
  23294. };
  23295. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23296. if (this._renderingGroups[renderingGroupId] === undefined) {
  23297. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23298. }
  23299. };
  23300. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23301. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23302. this._prepareRenderingGroup(renderingGroupId);
  23303. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23304. };
  23305. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23306. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23307. this._prepareRenderingGroup(renderingGroupId);
  23308. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23309. };
  23310. /**
  23311. * @param subMesh The submesh to dispatch
  23312. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23313. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23314. */
  23315. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23316. if (mesh === undefined) {
  23317. mesh = subMesh.getMesh();
  23318. }
  23319. var renderingGroupId = mesh.renderingGroupId || 0;
  23320. this._prepareRenderingGroup(renderingGroupId);
  23321. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23322. };
  23323. /**
  23324. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23325. * This allowed control for front to back rendering or reversly depending of the special needs.
  23326. *
  23327. * @param renderingGroupId The rendering group id corresponding to its index
  23328. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23329. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23330. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23331. */
  23332. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23333. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23334. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23335. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23336. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23337. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23338. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23339. if (this._renderingGroups[renderingGroupId]) {
  23340. var group = this._renderingGroups[renderingGroupId];
  23341. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23342. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23343. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23344. }
  23345. };
  23346. /**
  23347. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23348. *
  23349. * @param renderingGroupId The rendering group id corresponding to its index
  23350. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23351. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23352. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23353. */
  23354. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23355. if (depth === void 0) { depth = true; }
  23356. if (stencil === void 0) { stencil = true; }
  23357. this._autoClearDepthStencil[renderingGroupId] = {
  23358. autoClear: autoClearDepthStencil,
  23359. depth: depth,
  23360. stencil: stencil
  23361. };
  23362. };
  23363. /**
  23364. * The max id used for rendering groups (not included)
  23365. */
  23366. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23367. /**
  23368. * The min id used for rendering groups (included)
  23369. */
  23370. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23371. /**
  23372. * Used to globally prevent autoclearing scenes.
  23373. */
  23374. RenderingManager.AUTOCLEAR = true;
  23375. return RenderingManager;
  23376. }());
  23377. BABYLON.RenderingManager = RenderingManager;
  23378. })(BABYLON || (BABYLON = {}));
  23379. //# sourceMappingURL=babylon.renderingManager.js.map
  23380. var BABYLON;
  23381. (function (BABYLON) {
  23382. var RenderingGroup = /** @class */ (function () {
  23383. /**
  23384. * Creates a new rendering group.
  23385. * @param index The rendering group index
  23386. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23387. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23388. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23389. */
  23390. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23391. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23392. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23393. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23394. this.index = index;
  23395. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23396. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23397. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23398. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23399. this._particleSystems = new BABYLON.SmartArray(256);
  23400. this._spriteManagers = new BABYLON.SmartArray(256);
  23401. this._edgesRenderers = new BABYLON.SmartArray(16);
  23402. this._scene = scene;
  23403. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23404. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23405. this.transparentSortCompareFn = transparentSortCompareFn;
  23406. }
  23407. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23408. /**
  23409. * Set the opaque sort comparison function.
  23410. * If null the sub meshes will be render in the order they were created
  23411. */
  23412. set: function (value) {
  23413. this._opaqueSortCompareFn = value;
  23414. if (value) {
  23415. this._renderOpaque = this.renderOpaqueSorted;
  23416. }
  23417. else {
  23418. this._renderOpaque = RenderingGroup.renderUnsorted;
  23419. }
  23420. },
  23421. enumerable: true,
  23422. configurable: true
  23423. });
  23424. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23425. /**
  23426. * Set the alpha test sort comparison function.
  23427. * If null the sub meshes will be render in the order they were created
  23428. */
  23429. set: function (value) {
  23430. this._alphaTestSortCompareFn = value;
  23431. if (value) {
  23432. this._renderAlphaTest = this.renderAlphaTestSorted;
  23433. }
  23434. else {
  23435. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23436. }
  23437. },
  23438. enumerable: true,
  23439. configurable: true
  23440. });
  23441. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23442. /**
  23443. * Set the transparent sort comparison function.
  23444. * If null the sub meshes will be render in the order they were created
  23445. */
  23446. set: function (value) {
  23447. if (value) {
  23448. this._transparentSortCompareFn = value;
  23449. }
  23450. else {
  23451. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23452. }
  23453. this._renderTransparent = this.renderTransparentSorted;
  23454. },
  23455. enumerable: true,
  23456. configurable: true
  23457. });
  23458. /**
  23459. * Render all the sub meshes contained in the group.
  23460. * @param customRenderFunction Used to override the default render behaviour of the group.
  23461. * @returns true if rendered some submeshes.
  23462. */
  23463. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23464. if (customRenderFunction) {
  23465. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23466. return;
  23467. }
  23468. var engine = this._scene.getEngine();
  23469. // Depth only
  23470. if (this._depthOnlySubMeshes.length !== 0) {
  23471. engine.setColorWrite(false);
  23472. this._renderAlphaTest(this._depthOnlySubMeshes);
  23473. engine.setColorWrite(true);
  23474. }
  23475. // Opaque
  23476. if (this._opaqueSubMeshes.length !== 0) {
  23477. this._renderOpaque(this._opaqueSubMeshes);
  23478. }
  23479. // Alpha test
  23480. if (this._alphaTestSubMeshes.length !== 0) {
  23481. this._renderAlphaTest(this._alphaTestSubMeshes);
  23482. }
  23483. var stencilState = engine.getStencilBuffer();
  23484. engine.setStencilBuffer(false);
  23485. // Sprites
  23486. if (renderSprites) {
  23487. this._renderSprites();
  23488. }
  23489. // Particles
  23490. if (renderParticles) {
  23491. this._renderParticles(activeMeshes);
  23492. }
  23493. if (this.onBeforeTransparentRendering) {
  23494. this.onBeforeTransparentRendering();
  23495. }
  23496. // Transparent
  23497. if (this._transparentSubMeshes.length !== 0) {
  23498. this._renderTransparent(this._transparentSubMeshes);
  23499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23500. }
  23501. // Set back stencil to false in case it changes before the edge renderer.
  23502. engine.setStencilBuffer(false);
  23503. // Edges
  23504. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23505. this._edgesRenderers.data[edgesRendererIndex].render();
  23506. }
  23507. // Restore Stencil state.
  23508. engine.setStencilBuffer(stencilState);
  23509. };
  23510. /**
  23511. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23512. * @param subMeshes The submeshes to render
  23513. */
  23514. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23515. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23516. };
  23517. /**
  23518. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23519. * @param subMeshes The submeshes to render
  23520. */
  23521. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23522. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23523. };
  23524. /**
  23525. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23526. * @param subMeshes The submeshes to render
  23527. */
  23528. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23529. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23530. };
  23531. /**
  23532. * Renders the submeshes in a specified order.
  23533. * @param subMeshes The submeshes to sort before render
  23534. * @param sortCompareFn The comparison function use to sort
  23535. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23536. * @param transparent Specifies to activate blending if true
  23537. */
  23538. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23539. var subIndex = 0;
  23540. var subMesh;
  23541. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23542. for (; subIndex < subMeshes.length; subIndex++) {
  23543. subMesh = subMeshes.data[subIndex];
  23544. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23545. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23546. }
  23547. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23548. if (sortCompareFn) {
  23549. sortedArray.sort(sortCompareFn);
  23550. }
  23551. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23552. subMesh = sortedArray[subIndex];
  23553. if (transparent) {
  23554. var material = subMesh.getMaterial();
  23555. if (material && material.needDepthPrePass) {
  23556. var engine = material.getScene().getEngine();
  23557. engine.setColorWrite(false);
  23558. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23559. subMesh.render(false);
  23560. engine.setColorWrite(true);
  23561. }
  23562. }
  23563. subMesh.render(transparent);
  23564. }
  23565. };
  23566. /**
  23567. * Renders the submeshes in the order they were dispatched (no sort applied).
  23568. * @param subMeshes The submeshes to render
  23569. */
  23570. RenderingGroup.renderUnsorted = function (subMeshes) {
  23571. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23572. var submesh = subMeshes.data[subIndex];
  23573. submesh.render(false);
  23574. }
  23575. };
  23576. /**
  23577. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23578. * are rendered back to front if in the same alpha index.
  23579. *
  23580. * @param a The first submesh
  23581. * @param b The second submesh
  23582. * @returns The result of the comparison
  23583. */
  23584. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23585. // Alpha index first
  23586. if (a._alphaIndex > b._alphaIndex) {
  23587. return 1;
  23588. }
  23589. if (a._alphaIndex < b._alphaIndex) {
  23590. return -1;
  23591. }
  23592. // Then distance to camera
  23593. return RenderingGroup.backToFrontSortCompare(a, b);
  23594. };
  23595. /**
  23596. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23597. * are rendered back to front.
  23598. *
  23599. * @param a The first submesh
  23600. * @param b The second submesh
  23601. * @returns The result of the comparison
  23602. */
  23603. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23604. // Then distance to camera
  23605. if (a._distanceToCamera < b._distanceToCamera) {
  23606. return 1;
  23607. }
  23608. if (a._distanceToCamera > b._distanceToCamera) {
  23609. return -1;
  23610. }
  23611. return 0;
  23612. };
  23613. /**
  23614. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23615. * are rendered front to back (prevent overdraw).
  23616. *
  23617. * @param a The first submesh
  23618. * @param b The second submesh
  23619. * @returns The result of the comparison
  23620. */
  23621. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23622. // Then distance to camera
  23623. if (a._distanceToCamera < b._distanceToCamera) {
  23624. return -1;
  23625. }
  23626. if (a._distanceToCamera > b._distanceToCamera) {
  23627. return 1;
  23628. }
  23629. return 0;
  23630. };
  23631. /**
  23632. * Resets the different lists of submeshes to prepare a new frame.
  23633. */
  23634. RenderingGroup.prototype.prepare = function () {
  23635. this._opaqueSubMeshes.reset();
  23636. this._transparentSubMeshes.reset();
  23637. this._alphaTestSubMeshes.reset();
  23638. this._depthOnlySubMeshes.reset();
  23639. this._particleSystems.reset();
  23640. this._spriteManagers.reset();
  23641. this._edgesRenderers.reset();
  23642. };
  23643. RenderingGroup.prototype.dispose = function () {
  23644. this._opaqueSubMeshes.dispose();
  23645. this._transparentSubMeshes.dispose();
  23646. this._alphaTestSubMeshes.dispose();
  23647. this._depthOnlySubMeshes.dispose();
  23648. this._particleSystems.dispose();
  23649. this._spriteManagers.dispose();
  23650. this._edgesRenderers.dispose();
  23651. };
  23652. /**
  23653. * Inserts the submesh in its correct queue depending on its material.
  23654. * @param subMesh The submesh to dispatch
  23655. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23656. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23657. */
  23658. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23659. // Get mesh and materials if not provided
  23660. if (mesh === undefined) {
  23661. mesh = subMesh.getMesh();
  23662. }
  23663. if (material === undefined) {
  23664. material = subMesh.getMaterial();
  23665. }
  23666. if (material === null || material === undefined) {
  23667. return;
  23668. }
  23669. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23670. this._transparentSubMeshes.push(subMesh);
  23671. }
  23672. else if (material.needAlphaTesting()) { // Alpha test
  23673. if (material.needDepthPrePass) {
  23674. this._depthOnlySubMeshes.push(subMesh);
  23675. }
  23676. this._alphaTestSubMeshes.push(subMesh);
  23677. }
  23678. else {
  23679. if (material.needDepthPrePass) {
  23680. this._depthOnlySubMeshes.push(subMesh);
  23681. }
  23682. this._opaqueSubMeshes.push(subMesh); // Opaque
  23683. }
  23684. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23685. this._edgesRenderers.push(mesh._edgesRenderer);
  23686. }
  23687. };
  23688. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23689. this._spriteManagers.push(spriteManager);
  23690. };
  23691. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23692. this._particleSystems.push(particleSystem);
  23693. };
  23694. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23695. if (this._particleSystems.length === 0) {
  23696. return;
  23697. }
  23698. // Particles
  23699. var activeCamera = this._scene.activeCamera;
  23700. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23701. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23702. var particleSystem = this._particleSystems.data[particleIndex];
  23703. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23704. continue;
  23705. }
  23706. var emitter = particleSystem.emitter;
  23707. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23708. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23709. }
  23710. }
  23711. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23712. };
  23713. RenderingGroup.prototype._renderSprites = function () {
  23714. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23715. return;
  23716. }
  23717. // Sprites
  23718. var activeCamera = this._scene.activeCamera;
  23719. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23720. for (var id = 0; id < this._spriteManagers.length; id++) {
  23721. var spriteManager = this._spriteManagers.data[id];
  23722. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23723. spriteManager.render();
  23724. }
  23725. }
  23726. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23727. };
  23728. return RenderingGroup;
  23729. }());
  23730. BABYLON.RenderingGroup = RenderingGroup;
  23731. })(BABYLON || (BABYLON = {}));
  23732. //# sourceMappingURL=babylon.renderingGroup.js.map
  23733. var BABYLON;
  23734. (function (BABYLON) {
  23735. /** @hidden */
  23736. var ClickInfo = /** @class */ (function () {
  23737. function ClickInfo() {
  23738. this._singleClick = false;
  23739. this._doubleClick = false;
  23740. this._hasSwiped = false;
  23741. this._ignore = false;
  23742. }
  23743. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23744. get: function () {
  23745. return this._singleClick;
  23746. },
  23747. set: function (b) {
  23748. this._singleClick = b;
  23749. },
  23750. enumerable: true,
  23751. configurable: true
  23752. });
  23753. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23754. get: function () {
  23755. return this._doubleClick;
  23756. },
  23757. set: function (b) {
  23758. this._doubleClick = b;
  23759. },
  23760. enumerable: true,
  23761. configurable: true
  23762. });
  23763. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23764. get: function () {
  23765. return this._hasSwiped;
  23766. },
  23767. set: function (b) {
  23768. this._hasSwiped = b;
  23769. },
  23770. enumerable: true,
  23771. configurable: true
  23772. });
  23773. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23774. get: function () {
  23775. return this._ignore;
  23776. },
  23777. set: function (b) {
  23778. this._ignore = b;
  23779. },
  23780. enumerable: true,
  23781. configurable: true
  23782. });
  23783. return ClickInfo;
  23784. }());
  23785. /**
  23786. * This class is used by the onRenderingGroupObservable
  23787. */
  23788. var RenderingGroupInfo = /** @class */ (function () {
  23789. function RenderingGroupInfo() {
  23790. }
  23791. /**
  23792. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23793. * This stage will be fired no matter what
  23794. */
  23795. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23796. /**
  23797. * Called before opaque object are rendered.
  23798. * This stage will be fired only if there's 3D Opaque content to render
  23799. */
  23800. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23801. /**
  23802. * Called after the opaque objects are rendered and before the transparent ones
  23803. * This stage will be fired only if there's 3D transparent content to render
  23804. */
  23805. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23806. /**
  23807. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23808. * This stage will be fired no matter what
  23809. */
  23810. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23811. return RenderingGroupInfo;
  23812. }());
  23813. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23814. /**
  23815. * Represents a scene to be rendered by the engine.
  23816. * @see http://doc.babylonjs.com/features/scene
  23817. */
  23818. var Scene = /** @class */ (function () {
  23819. /**
  23820. * Creates a new Scene
  23821. * @param engine defines the engine to use to render this scene
  23822. */
  23823. function Scene(engine) {
  23824. // Members
  23825. /**
  23826. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23827. */
  23828. this.autoClear = true;
  23829. /**
  23830. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23831. */
  23832. this.autoClearDepthAndStencil = true;
  23833. /**
  23834. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23835. */
  23836. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23837. /**
  23838. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23839. */
  23840. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23841. this._forceWireframe = false;
  23842. this._forcePointsCloud = false;
  23843. /**
  23844. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23845. */
  23846. this.forceShowBoundingBoxes = false;
  23847. /**
  23848. * Gets or sets a boolean indicating if animations are enabled
  23849. */
  23850. this.animationsEnabled = true;
  23851. this._animationPropertiesOverride = null;
  23852. /**
  23853. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23854. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23855. */
  23856. this.useConstantAnimationDeltaTime = false;
  23857. /**
  23858. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23859. * Please note that it requires to run a ray cast through the scene on every frame
  23860. */
  23861. this.constantlyUpdateMeshUnderPointer = false;
  23862. /**
  23863. * Defines the HTML cursor to use when hovering over interactive elements
  23864. */
  23865. this.hoverCursor = "pointer";
  23866. /**
  23867. * Defines the HTML default cursor to use (empty by default)
  23868. */
  23869. this.defaultCursor = "";
  23870. /**
  23871. * This is used to call preventDefault() on pointer down
  23872. * in order to block unwanted artifacts like system double clicks
  23873. */
  23874. this.preventDefaultOnPointerDown = true;
  23875. // Metadata
  23876. /**
  23877. * Gets or sets user defined metadata
  23878. */
  23879. this.metadata = null;
  23880. /**
  23881. * Use this array to add regular expressions used to disable offline support for specific urls
  23882. */
  23883. this.disableOfflineSupportExceptionRules = new Array();
  23884. /**
  23885. * An event triggered when the scene is disposed.
  23886. */
  23887. this.onDisposeObservable = new BABYLON.Observable();
  23888. this._onDisposeObserver = null;
  23889. /**
  23890. * An event triggered before rendering the scene (right after animations and physics)
  23891. */
  23892. this.onBeforeRenderObservable = new BABYLON.Observable();
  23893. this._onBeforeRenderObserver = null;
  23894. /**
  23895. * An event triggered after rendering the scene
  23896. */
  23897. this.onAfterRenderObservable = new BABYLON.Observable();
  23898. this._onAfterRenderObserver = null;
  23899. /**
  23900. * An event triggered before animating the scene
  23901. */
  23902. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23903. /**
  23904. * An event triggered after animations processing
  23905. */
  23906. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23907. /**
  23908. * An event triggered before draw calls are ready to be sent
  23909. */
  23910. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23911. /**
  23912. * An event triggered after draw calls have been sent
  23913. */
  23914. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23915. /**
  23916. * An event triggered when physic simulation is about to be run
  23917. */
  23918. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23919. /**
  23920. * An event triggered when physic simulation has been done
  23921. */
  23922. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23923. /**
  23924. * An event triggered when the scene is ready
  23925. */
  23926. this.onReadyObservable = new BABYLON.Observable();
  23927. /**
  23928. * An event triggered before rendering a camera
  23929. */
  23930. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23931. this._onBeforeCameraRenderObserver = null;
  23932. /**
  23933. * An event triggered after rendering a camera
  23934. */
  23935. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23936. this._onAfterCameraRenderObserver = null;
  23937. /**
  23938. * An event triggered when active meshes evaluation is about to start
  23939. */
  23940. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23941. /**
  23942. * An event triggered when active meshes evaluation is done
  23943. */
  23944. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23945. /**
  23946. * An event triggered when particles rendering is about to start
  23947. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23948. */
  23949. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23950. /**
  23951. * An event triggered when particles rendering is done
  23952. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23953. */
  23954. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23955. /**
  23956. * An event triggered when sprites rendering is about to start
  23957. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23958. */
  23959. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23960. /**
  23961. * An event triggered when sprites rendering is done
  23962. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23963. */
  23964. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23965. /**
  23966. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23967. */
  23968. this.onDataLoadedObservable = new BABYLON.Observable();
  23969. /**
  23970. * An event triggered when a camera is created
  23971. */
  23972. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23973. /**
  23974. * An event triggered when a camera is removed
  23975. */
  23976. this.onCameraRemovedObservable = new BABYLON.Observable();
  23977. /**
  23978. * An event triggered when a light is created
  23979. */
  23980. this.onNewLightAddedObservable = new BABYLON.Observable();
  23981. /**
  23982. * An event triggered when a light is removed
  23983. */
  23984. this.onLightRemovedObservable = new BABYLON.Observable();
  23985. /**
  23986. * An event triggered when a geometry is created
  23987. */
  23988. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23989. /**
  23990. * An event triggered when a geometry is removed
  23991. */
  23992. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23993. /**
  23994. * An event triggered when a transform node is created
  23995. */
  23996. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23997. /**
  23998. * An event triggered when a transform node is removed
  23999. */
  24000. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24001. /**
  24002. * An event triggered when a mesh is created
  24003. */
  24004. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24005. /**
  24006. * An event triggered when a mesh is removed
  24007. */
  24008. this.onMeshRemovedObservable = new BABYLON.Observable();
  24009. /**
  24010. * An event triggered when render targets are about to be rendered
  24011. * Can happen multiple times per frame.
  24012. */
  24013. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when render targets were rendered.
  24016. * Can happen multiple times per frame.
  24017. */
  24018. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24019. /**
  24020. * An event triggered before calculating deterministic simulation step
  24021. */
  24022. this.onBeforeStepObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered after calculating deterministic simulation step
  24025. */
  24026. this.onAfterStepObservable = new BABYLON.Observable();
  24027. /**
  24028. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24029. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24030. * 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)
  24031. */
  24032. this.onRenderingGroupObservable = new BABYLON.Observable();
  24033. // Animations
  24034. /**
  24035. * Gets a list of Animations associated with the scene
  24036. */
  24037. this.animations = [];
  24038. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24039. /**
  24040. * 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).
  24041. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24042. */
  24043. this.onPrePointerObservable = new BABYLON.Observable();
  24044. /**
  24045. * Observable event triggered each time an input event is received from the rendering canvas
  24046. */
  24047. this.onPointerObservable = new BABYLON.Observable();
  24048. this._meshPickProceed = false;
  24049. this._currentPickResult = null;
  24050. this._previousPickResult = null;
  24051. this._totalPointersPressed = 0;
  24052. this._doubleClickOccured = false;
  24053. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24054. this.cameraToUseForPointers = null;
  24055. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24056. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24057. this._startingPointerTime = 0;
  24058. this._previousStartingPointerTime = 0;
  24059. this._pointerCaptures = {};
  24060. // Deterministic lockstep
  24061. this._timeAccumulator = 0;
  24062. this._currentStepId = 0;
  24063. this._currentInternalStep = 0;
  24064. // Keyboard
  24065. /**
  24066. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24067. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24068. */
  24069. this.onPreKeyboardObservable = new BABYLON.Observable();
  24070. /**
  24071. * Observable event triggered each time an keyboard event is received from the hosting window
  24072. */
  24073. this.onKeyboardObservable = new BABYLON.Observable();
  24074. // Coordinates system
  24075. this._useRightHandedSystem = false;
  24076. // Fog
  24077. this._fogEnabled = true;
  24078. this._fogMode = Scene.FOGMODE_NONE;
  24079. /**
  24080. * Gets or sets the fog color to use
  24081. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24082. */
  24083. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24084. /**
  24085. * Gets or sets the fog density to use
  24086. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24087. */
  24088. this.fogDensity = 0.1;
  24089. /**
  24090. * Gets or sets the fog start distance to use
  24091. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24092. */
  24093. this.fogStart = 0;
  24094. /**
  24095. * Gets or sets the fog end distance to use
  24096. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24097. */
  24098. this.fogEnd = 1000.0;
  24099. // Lights
  24100. this._shadowsEnabled = true;
  24101. this._lightsEnabled = true;
  24102. /**
  24103. * All of the lights added to this scene
  24104. * @see http://doc.babylonjs.com/babylon101/lights
  24105. */
  24106. this.lights = new Array();
  24107. // Cameras
  24108. /** All of the cameras added to this scene.
  24109. * @see http://doc.babylonjs.com/babylon101/cameras
  24110. */
  24111. this.cameras = new Array();
  24112. /** All of the active cameras added to this scene. */
  24113. this.activeCameras = new Array();
  24114. // Meshes
  24115. /**
  24116. * All of the tranform nodes added to this scene
  24117. * @see http://doc.babylonjs.com/how_to/transformnode
  24118. */
  24119. this.transformNodes = new Array();
  24120. /**
  24121. * All of the (abstract) meshes added to this scene
  24122. */
  24123. this.meshes = new Array();
  24124. /**
  24125. * All of the animation groups added to this scene
  24126. * @see http://doc.babylonjs.com/how_to/group
  24127. */
  24128. this.animationGroups = new Array();
  24129. // Geometries
  24130. this._geometries = new Array();
  24131. /**
  24132. * All of the materials added to this scene
  24133. * @see http://doc.babylonjs.com/babylon101/materials
  24134. */
  24135. this.materials = new Array();
  24136. /**
  24137. * All of the multi-materials added to this scene
  24138. * @see http://doc.babylonjs.com/how_to/multi_materials
  24139. */
  24140. this.multiMaterials = new Array();
  24141. // Textures
  24142. this._texturesEnabled = true;
  24143. /**
  24144. * All of the textures added to this scene
  24145. */
  24146. this.textures = new Array();
  24147. // Particles
  24148. /**
  24149. * Gets or sets a boolean indicating if particles are enabled on this scene
  24150. */
  24151. this.particlesEnabled = true;
  24152. /**
  24153. * All of the particle systems added to this scene
  24154. * @see http://doc.babylonjs.com/babylon101/particles
  24155. */
  24156. this.particleSystems = new Array();
  24157. // Sprites
  24158. /**
  24159. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24160. */
  24161. this.spritesEnabled = true;
  24162. /**
  24163. * All of the sprite managers added to this scene
  24164. * @see http://doc.babylonjs.com/babylon101/sprites
  24165. */
  24166. this.spriteManagers = new Array();
  24167. /**
  24168. * The list of layers (background and foreground) of the scene
  24169. */
  24170. this.layers = new Array();
  24171. /**
  24172. * The list of effect layers (highlights/glow) added to the scene
  24173. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24174. * @see http://doc.babylonjs.com/how_to/glow_layer
  24175. */
  24176. this.effectLayers = new Array();
  24177. // Skeletons
  24178. this._skeletonsEnabled = true;
  24179. /**
  24180. * The list of skeletons added to the scene
  24181. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24182. */
  24183. this.skeletons = new Array();
  24184. // Morph targets
  24185. /**
  24186. * The list of morph target managers added to the scene
  24187. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24188. */
  24189. this.morphTargetManagers = new Array();
  24190. // Lens flares
  24191. /**
  24192. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24193. */
  24194. this.lensFlaresEnabled = true;
  24195. /**
  24196. * The list of lens flare system added to the scene
  24197. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24198. */
  24199. this.lensFlareSystems = new Array();
  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. /** @hidden */
  24249. this._actionManagers = new Array();
  24250. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24251. // Procedural textures
  24252. /**
  24253. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24254. */
  24255. this.proceduralTexturesEnabled = true;
  24256. /**
  24257. * The list of procedural textures added to the scene
  24258. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24259. */
  24260. this.proceduralTextures = new Array();
  24261. /**
  24262. * The list of sound tracks added to the scene
  24263. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24264. */
  24265. this.soundTracks = new Array();
  24266. this._audioEnabled = true;
  24267. this._headphone = false;
  24268. // Performance counters
  24269. this._totalVertices = new BABYLON.PerfCounter();
  24270. /** @hidden */
  24271. this._activeIndices = new BABYLON.PerfCounter();
  24272. /** @hidden */
  24273. this._activeParticles = new BABYLON.PerfCounter();
  24274. /** @hidden */
  24275. this._activeBones = new BABYLON.PerfCounter();
  24276. this._animationTime = 0;
  24277. /**
  24278. * Gets or sets a general scale for animation speed
  24279. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24280. */
  24281. this.animationTimeScale = 1;
  24282. this._renderId = 0;
  24283. this._executeWhenReadyTimeoutId = -1;
  24284. this._intermediateRendering = false;
  24285. this._viewUpdateFlag = -1;
  24286. this._projectionUpdateFlag = -1;
  24287. this._alternateViewUpdateFlag = -1;
  24288. this._alternateProjectionUpdateFlag = -1;
  24289. /** @hidden */
  24290. this._toBeDisposed = new BABYLON.SmartArray(256);
  24291. this._activeRequests = new Array();
  24292. this._pendingData = new Array();
  24293. this._isDisposed = false;
  24294. /**
  24295. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24296. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24297. */
  24298. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24299. this._activeMeshes = new BABYLON.SmartArray(256);
  24300. this._processedMaterials = new BABYLON.SmartArray(256);
  24301. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24302. /** @hidden */
  24303. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24304. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24305. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24306. /** @hidden */
  24307. this._activeAnimatables = new Array();
  24308. this._transformMatrix = BABYLON.Matrix.Zero();
  24309. this._useAlternateCameraConfiguration = false;
  24310. this._alternateRendering = false;
  24311. /**
  24312. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24313. * This is useful if there are more lights that the maximum simulteanous authorized
  24314. */
  24315. this.requireLightSorting = false;
  24316. this._depthRenderer = {};
  24317. this._activeMeshesFrozen = false;
  24318. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24319. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24320. this._engine.scenes.push(this);
  24321. this._uid = null;
  24322. this._renderingManager = new BABYLON.RenderingManager(this);
  24323. if (BABYLON.PostProcessManager) {
  24324. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24325. }
  24326. if (BABYLON.OutlineRenderer) {
  24327. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24328. }
  24329. if (BABYLON.Tools.IsWindowObjectExist()) {
  24330. this.attachControl();
  24331. }
  24332. //simplification queue
  24333. if (BABYLON.SimplificationQueue) {
  24334. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24335. }
  24336. //collision coordinator initialization. For now legacy per default.
  24337. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24338. // Uniform Buffer
  24339. this._createUbo();
  24340. // Default Image processing definition
  24341. if (BABYLON.ImageProcessingConfiguration) {
  24342. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24343. }
  24344. }
  24345. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24346. /** The fog is deactivated */
  24347. get: function () {
  24348. return Scene._FOGMODE_NONE;
  24349. },
  24350. enumerable: true,
  24351. configurable: true
  24352. });
  24353. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24354. /** The fog density is following an exponential function */
  24355. get: function () {
  24356. return Scene._FOGMODE_EXP;
  24357. },
  24358. enumerable: true,
  24359. configurable: true
  24360. });
  24361. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24362. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24363. get: function () {
  24364. return Scene._FOGMODE_EXP2;
  24365. },
  24366. enumerable: true,
  24367. configurable: true
  24368. });
  24369. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24370. /** The fog density is following a linear function. */
  24371. get: function () {
  24372. return Scene._FOGMODE_LINEAR;
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24378. /**
  24379. * Texture used in all pbr material as the reflection texture.
  24380. * As in the majority of the scene they are the same (exception for multi room and so on),
  24381. * this is easier to reference from here than from all the materials.
  24382. */
  24383. get: function () {
  24384. return this._environmentTexture;
  24385. },
  24386. /**
  24387. * Texture used in all pbr material as the reflection texture.
  24388. * As in the majority of the scene they are the same (exception for multi room and so on),
  24389. * this is easier to set here than in all the materials.
  24390. */
  24391. set: function (value) {
  24392. if (this._environmentTexture === value) {
  24393. return;
  24394. }
  24395. this._environmentTexture = value;
  24396. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24397. },
  24398. enumerable: true,
  24399. configurable: true
  24400. });
  24401. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24402. /**
  24403. * Default image processing configuration used either in the rendering
  24404. * Forward main pass or through the imageProcessingPostProcess if present.
  24405. * As in the majority of the scene they are the same (exception for multi camera),
  24406. * this is easier to reference from here than from all the materials and post process.
  24407. *
  24408. * No setter as we it is a shared configuration, you can set the values instead.
  24409. */
  24410. get: function () {
  24411. return this._imageProcessingConfiguration;
  24412. },
  24413. enumerable: true,
  24414. configurable: true
  24415. });
  24416. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24417. get: function () {
  24418. return this._forceWireframe;
  24419. },
  24420. /**
  24421. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24422. */
  24423. set: function (value) {
  24424. if (this._forceWireframe === value) {
  24425. return;
  24426. }
  24427. this._forceWireframe = value;
  24428. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24434. get: function () {
  24435. return this._forcePointsCloud;
  24436. },
  24437. /**
  24438. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24439. */
  24440. set: function (value) {
  24441. if (this._forcePointsCloud === value) {
  24442. return;
  24443. }
  24444. this._forcePointsCloud = value;
  24445. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24451. /**
  24452. * Gets or sets the animation properties override
  24453. */
  24454. get: function () {
  24455. return this._animationPropertiesOverride;
  24456. },
  24457. set: function (value) {
  24458. this._animationPropertiesOverride = value;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "onDispose", {
  24464. /** Sets a function to be executed when this scene is disposed. */
  24465. set: function (callback) {
  24466. if (this._onDisposeObserver) {
  24467. this.onDisposeObservable.remove(this._onDisposeObserver);
  24468. }
  24469. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24470. },
  24471. enumerable: true,
  24472. configurable: true
  24473. });
  24474. Object.defineProperty(Scene.prototype, "beforeRender", {
  24475. /** Sets a function to be executed before rendering this scene */
  24476. set: function (callback) {
  24477. if (this._onBeforeRenderObserver) {
  24478. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24479. }
  24480. if (callback) {
  24481. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24482. }
  24483. },
  24484. enumerable: true,
  24485. configurable: true
  24486. });
  24487. Object.defineProperty(Scene.prototype, "afterRender", {
  24488. /** Sets a function to be executed after rendering this scene */
  24489. set: function (callback) {
  24490. if (this._onAfterRenderObserver) {
  24491. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24492. }
  24493. if (callback) {
  24494. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24495. }
  24496. },
  24497. enumerable: true,
  24498. configurable: true
  24499. });
  24500. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24501. /** Sets a function to be executed before rendering a camera*/
  24502. set: function (callback) {
  24503. if (this._onBeforeCameraRenderObserver) {
  24504. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24505. }
  24506. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24507. },
  24508. enumerable: true,
  24509. configurable: true
  24510. });
  24511. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24512. /** Sets a function to be executed after rendering a camera*/
  24513. set: function (callback) {
  24514. if (this._onAfterCameraRenderObserver) {
  24515. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24516. }
  24517. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24518. },
  24519. enumerable: true,
  24520. configurable: true
  24521. });
  24522. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24523. /**
  24524. * Gets the gamepad manager associated with the scene
  24525. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24526. */
  24527. get: function () {
  24528. if (!this._gamepadManager) {
  24529. this._gamepadManager = new BABYLON.GamepadManager(this);
  24530. }
  24531. return this._gamepadManager;
  24532. },
  24533. enumerable: true,
  24534. configurable: true
  24535. });
  24536. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24537. /**
  24538. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24539. */
  24540. get: function () {
  24541. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24542. },
  24543. enumerable: true,
  24544. configurable: true
  24545. });
  24546. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24547. get: function () {
  24548. return this._useRightHandedSystem;
  24549. },
  24550. /**
  24551. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24552. */
  24553. set: function (value) {
  24554. if (this._useRightHandedSystem === value) {
  24555. return;
  24556. }
  24557. this._useRightHandedSystem = value;
  24558. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. /**
  24564. * Sets the step Id used by deterministic lock step
  24565. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24566. * @param newStepId defines the step Id
  24567. */
  24568. Scene.prototype.setStepId = function (newStepId) {
  24569. this._currentStepId = newStepId;
  24570. };
  24571. ;
  24572. /**
  24573. * Gets the step Id used by deterministic lock step
  24574. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24575. * @returns the step Id
  24576. */
  24577. Scene.prototype.getStepId = function () {
  24578. return this._currentStepId;
  24579. };
  24580. ;
  24581. /**
  24582. * Gets the internal step used by deterministic lock step
  24583. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24584. * @returns the internal step
  24585. */
  24586. Scene.prototype.getInternalStep = function () {
  24587. return this._currentInternalStep;
  24588. };
  24589. ;
  24590. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24591. get: function () {
  24592. return this._fogEnabled;
  24593. },
  24594. /**
  24595. * Gets or sets a boolean indicating if fog is enabled on this scene
  24596. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24597. */
  24598. set: function (value) {
  24599. if (this._fogEnabled === value) {
  24600. return;
  24601. }
  24602. this._fogEnabled = value;
  24603. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Scene.prototype, "fogMode", {
  24609. get: function () {
  24610. return this._fogMode;
  24611. },
  24612. /**
  24613. * Gets or sets the fog mode to use
  24614. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24615. */
  24616. set: function (value) {
  24617. if (this._fogMode === value) {
  24618. return;
  24619. }
  24620. this._fogMode = value;
  24621. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24622. },
  24623. enumerable: true,
  24624. configurable: true
  24625. });
  24626. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24627. get: function () {
  24628. return this._shadowsEnabled;
  24629. },
  24630. /**
  24631. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24632. */
  24633. set: function (value) {
  24634. if (this._shadowsEnabled === value) {
  24635. return;
  24636. }
  24637. this._shadowsEnabled = value;
  24638. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24639. },
  24640. enumerable: true,
  24641. configurable: true
  24642. });
  24643. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24644. get: function () {
  24645. return this._lightsEnabled;
  24646. },
  24647. /**
  24648. * Gets or sets a boolean indicating if lights are enabled on this scene
  24649. */
  24650. set: function (value) {
  24651. if (this._lightsEnabled === value) {
  24652. return;
  24653. }
  24654. this._lightsEnabled = value;
  24655. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24656. },
  24657. enumerable: true,
  24658. configurable: true
  24659. });
  24660. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24661. /** The default material used on meshes when no material is affected */
  24662. get: function () {
  24663. if (!this._defaultMaterial) {
  24664. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24665. }
  24666. return this._defaultMaterial;
  24667. },
  24668. /** The default material used on meshes when no material is affected */
  24669. set: function (value) {
  24670. this._defaultMaterial = value;
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24676. get: function () {
  24677. return this._texturesEnabled;
  24678. },
  24679. /**
  24680. * Gets or sets a boolean indicating if textures are enabled on this scene
  24681. */
  24682. set: function (value) {
  24683. if (this._texturesEnabled === value) {
  24684. return;
  24685. }
  24686. this._texturesEnabled = value;
  24687. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24688. },
  24689. enumerable: true,
  24690. configurable: true
  24691. });
  24692. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24693. get: function () {
  24694. return this._skeletonsEnabled;
  24695. },
  24696. /**
  24697. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24698. */
  24699. set: function (value) {
  24700. if (this._skeletonsEnabled === value) {
  24701. return;
  24702. }
  24703. this._skeletonsEnabled = value;
  24704. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24705. },
  24706. enumerable: true,
  24707. configurable: true
  24708. });
  24709. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24710. /**
  24711. * Gets the postprocess render pipeline manager
  24712. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24713. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24714. */
  24715. get: function () {
  24716. if (!this._postProcessRenderPipelineManager) {
  24717. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24718. }
  24719. return this._postProcessRenderPipelineManager;
  24720. },
  24721. enumerable: true,
  24722. configurable: true
  24723. });
  24724. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24725. /**
  24726. * Gets the main soundtrack associated with the scene
  24727. */
  24728. get: function () {
  24729. if (!this._mainSoundTrack) {
  24730. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24731. }
  24732. return this._mainSoundTrack;
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24738. /** @hidden */
  24739. get: function () {
  24740. return this._alternateRendering;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24746. /**
  24747. * Gets the list of frustum planes (built from the active camera)
  24748. */
  24749. get: function () {
  24750. return this._frustumPlanes;
  24751. },
  24752. enumerable: true,
  24753. configurable: true
  24754. });
  24755. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24756. /**
  24757. * Gets the current geometry buffer associated to the scene.
  24758. */
  24759. get: function () {
  24760. return this._geometryBufferRenderer;
  24761. },
  24762. /**
  24763. * Sets the current geometry buffer for the scene.
  24764. */
  24765. set: function (geometryBufferRenderer) {
  24766. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24767. this._geometryBufferRenderer = geometryBufferRenderer;
  24768. }
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. Object.defineProperty(Scene.prototype, "debugLayer", {
  24774. /**
  24775. * Gets the debug layer (aka Inspector) associated with the scene
  24776. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24777. */
  24778. get: function () {
  24779. if (!this._debugLayer) {
  24780. this._debugLayer = new BABYLON.DebugLayer(this);
  24781. }
  24782. return this._debugLayer;
  24783. },
  24784. enumerable: true,
  24785. configurable: true
  24786. });
  24787. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24788. /**
  24789. * Gets a boolean indicating if collisions are processed on a web worker
  24790. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24791. */
  24792. get: function () {
  24793. return this._workerCollisions;
  24794. },
  24795. set: function (enabled) {
  24796. if (!BABYLON.CollisionCoordinatorLegacy) {
  24797. return;
  24798. }
  24799. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24800. this._workerCollisions = enabled;
  24801. if (this.collisionCoordinator) {
  24802. this.collisionCoordinator.destroy();
  24803. }
  24804. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24805. this.collisionCoordinator.init(this);
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24811. /**
  24812. * Gets the octree used to boost mesh selection (picking)
  24813. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24814. */
  24815. get: function () {
  24816. return this._selectionOctree;
  24817. },
  24818. enumerable: true,
  24819. configurable: true
  24820. });
  24821. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24822. /**
  24823. * Gets the mesh that is currently under the pointer
  24824. */
  24825. get: function () {
  24826. return this._pointerOverMesh;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(Scene.prototype, "pointerX", {
  24832. /**
  24833. * Gets the current on-screen X position of the pointer
  24834. */
  24835. get: function () {
  24836. return this._pointerX;
  24837. },
  24838. enumerable: true,
  24839. configurable: true
  24840. });
  24841. Object.defineProperty(Scene.prototype, "pointerY", {
  24842. /**
  24843. * Gets the current on-screen Y position of the pointer
  24844. */
  24845. get: function () {
  24846. return this._pointerY;
  24847. },
  24848. enumerable: true,
  24849. configurable: true
  24850. });
  24851. /**
  24852. * Gets the cached material (ie. the latest rendered one)
  24853. * @returns the cached material
  24854. */
  24855. Scene.prototype.getCachedMaterial = function () {
  24856. return this._cachedMaterial;
  24857. };
  24858. /**
  24859. * Gets the cached effect (ie. the latest rendered one)
  24860. * @returns the cached effect
  24861. */
  24862. Scene.prototype.getCachedEffect = function () {
  24863. return this._cachedEffect;
  24864. };
  24865. /**
  24866. * Gets the cached visibility state (ie. the latest rendered one)
  24867. * @returns the cached visibility state
  24868. */
  24869. Scene.prototype.getCachedVisibility = function () {
  24870. return this._cachedVisibility;
  24871. };
  24872. /**
  24873. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24874. * @param material defines the current material
  24875. * @param effect defines the current effect
  24876. * @param visibility defines the current visibility state
  24877. * @returns true if one parameter is not cached
  24878. */
  24879. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24880. if (visibility === void 0) { visibility = 1; }
  24881. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24882. };
  24883. /**
  24884. * Gets the bounding box renderer associated with the scene
  24885. * @returns a BoundingBoxRenderer
  24886. */
  24887. Scene.prototype.getBoundingBoxRenderer = function () {
  24888. if (!this._boundingBoxRenderer) {
  24889. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24890. }
  24891. return this._boundingBoxRenderer;
  24892. };
  24893. /**
  24894. * Gets the outline renderer associated with the scene
  24895. * @returns a OutlineRenderer
  24896. */
  24897. Scene.prototype.getOutlineRenderer = function () {
  24898. return this._outlineRenderer;
  24899. };
  24900. /**
  24901. * Gets the engine associated with the scene
  24902. * @returns an Engine
  24903. */
  24904. Scene.prototype.getEngine = function () {
  24905. return this._engine;
  24906. };
  24907. /**
  24908. * Gets the total number of vertices rendered per frame
  24909. * @returns the total number of vertices rendered per frame
  24910. */
  24911. Scene.prototype.getTotalVertices = function () {
  24912. return this._totalVertices.current;
  24913. };
  24914. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24915. /**
  24916. * Gets the performance counter for total vertices
  24917. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24918. */
  24919. get: function () {
  24920. return this._totalVertices;
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. /**
  24926. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24927. * @returns the total number of active indices rendered per frame
  24928. */
  24929. Scene.prototype.getActiveIndices = function () {
  24930. return this._activeIndices.current;
  24931. };
  24932. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24933. /**
  24934. * Gets the performance counter for active indices
  24935. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24936. */
  24937. get: function () {
  24938. return this._activeIndices;
  24939. },
  24940. enumerable: true,
  24941. configurable: true
  24942. });
  24943. /**
  24944. * Gets the total number of active particles rendered per frame
  24945. * @returns the total number of active particles rendered per frame
  24946. */
  24947. Scene.prototype.getActiveParticles = function () {
  24948. return this._activeParticles.current;
  24949. };
  24950. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24951. /**
  24952. * Gets the performance counter for active particles
  24953. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24954. */
  24955. get: function () {
  24956. return this._activeParticles;
  24957. },
  24958. enumerable: true,
  24959. configurable: true
  24960. });
  24961. /**
  24962. * Gets the total number of active bones rendered per frame
  24963. * @returns the total number of active bones rendered per frame
  24964. */
  24965. Scene.prototype.getActiveBones = function () {
  24966. return this._activeBones.current;
  24967. };
  24968. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24969. /**
  24970. * Gets the performance counter for active bones
  24971. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24972. */
  24973. get: function () {
  24974. return this._activeBones;
  24975. },
  24976. enumerable: true,
  24977. configurable: true
  24978. });
  24979. /** @hidden */
  24980. Scene.prototype.getInterFramePerfCounter = function () {
  24981. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24982. return 0;
  24983. };
  24984. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24985. /** @hidden */
  24986. get: function () {
  24987. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24988. return null;
  24989. },
  24990. enumerable: true,
  24991. configurable: true
  24992. });
  24993. /** @hidden */
  24994. Scene.prototype.getLastFrameDuration = function () {
  24995. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24996. return 0;
  24997. };
  24998. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24999. /** @hidden */
  25000. get: function () {
  25001. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25002. return null;
  25003. },
  25004. enumerable: true,
  25005. configurable: true
  25006. });
  25007. /** @hidden */
  25008. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25009. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25010. return 0;
  25011. };
  25012. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25013. /** @hidden */
  25014. get: function () {
  25015. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25016. return null;
  25017. },
  25018. enumerable: true,
  25019. configurable: true
  25020. });
  25021. /**
  25022. * Gets the array of active meshes
  25023. * @returns an array of AbstractMesh
  25024. */
  25025. Scene.prototype.getActiveMeshes = function () {
  25026. return this._activeMeshes;
  25027. };
  25028. /** @hidden */
  25029. Scene.prototype.getRenderTargetsDuration = function () {
  25030. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25031. return 0;
  25032. };
  25033. /** @hidden */
  25034. Scene.prototype.getRenderDuration = function () {
  25035. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25036. return 0;
  25037. };
  25038. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25039. /** @hidden */
  25040. get: function () {
  25041. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25042. return null;
  25043. },
  25044. enumerable: true,
  25045. configurable: true
  25046. });
  25047. /** @hidden */
  25048. Scene.prototype.getParticlesDuration = function () {
  25049. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25050. return 0;
  25051. };
  25052. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25053. /** @hidden */
  25054. get: function () {
  25055. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25056. return null;
  25057. },
  25058. enumerable: true,
  25059. configurable: true
  25060. });
  25061. /** @hidden */
  25062. Scene.prototype.getSpritesDuration = function () {
  25063. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25064. return 0;
  25065. };
  25066. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25067. /** @hidden */
  25068. get: function () {
  25069. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25070. return null;
  25071. },
  25072. enumerable: true,
  25073. configurable: true
  25074. });
  25075. /**
  25076. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25077. * @returns a number
  25078. */
  25079. Scene.prototype.getAnimationRatio = function () {
  25080. return this._animationRatio;
  25081. };
  25082. /**
  25083. * Gets an unique Id for the current frame
  25084. * @returns a number
  25085. */
  25086. Scene.prototype.getRenderId = function () {
  25087. return this._renderId;
  25088. };
  25089. /** Call this function if you want to manually increment the render Id*/
  25090. Scene.prototype.incrementRenderId = function () {
  25091. this._renderId++;
  25092. };
  25093. Scene.prototype._updatePointerPosition = function (evt) {
  25094. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25095. if (!canvasRect) {
  25096. return;
  25097. }
  25098. this._pointerX = evt.clientX - canvasRect.left;
  25099. this._pointerY = evt.clientY - canvasRect.top;
  25100. this._unTranslatedPointerX = this._pointerX;
  25101. this._unTranslatedPointerY = this._pointerY;
  25102. };
  25103. Scene.prototype._createUbo = function () {
  25104. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25105. this._sceneUbo.addUniform("viewProjection", 16);
  25106. this._sceneUbo.addUniform("view", 16);
  25107. };
  25108. Scene.prototype._createAlternateUbo = function () {
  25109. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25110. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25111. this._alternateSceneUbo.addUniform("view", 16);
  25112. };
  25113. // Pointers handling
  25114. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25115. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25116. if (result) {
  25117. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25118. }
  25119. return result;
  25120. };
  25121. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25122. if (pointerInfo.pickInfo) {
  25123. if (!pointerInfo.pickInfo.ray) {
  25124. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25125. }
  25126. }
  25127. };
  25128. /**
  25129. * Use this method to simulate a pointer move on a mesh
  25130. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25131. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25132. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25133. * @returns the current scene
  25134. */
  25135. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25136. var evt = new PointerEvent("pointermove", pointerEventInit);
  25137. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25138. return this;
  25139. }
  25140. return this._processPointerMove(pickResult, evt);
  25141. };
  25142. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25143. var canvas = this._engine.getRenderingCanvas();
  25144. if (!canvas) {
  25145. return this;
  25146. }
  25147. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25148. this.setPointerOverSprite(null);
  25149. this.setPointerOverMesh(pickResult.pickedMesh);
  25150. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25151. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25152. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25153. }
  25154. else {
  25155. canvas.style.cursor = this.hoverCursor;
  25156. }
  25157. }
  25158. else {
  25159. canvas.style.cursor = this.defaultCursor;
  25160. }
  25161. }
  25162. else {
  25163. this.setPointerOverMesh(null);
  25164. // Sprites
  25165. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25166. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25167. this.setPointerOverSprite(pickResult.pickedSprite);
  25168. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25169. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25170. }
  25171. else {
  25172. canvas.style.cursor = this.hoverCursor;
  25173. }
  25174. }
  25175. else {
  25176. this.setPointerOverSprite(null);
  25177. // Restore pointer
  25178. canvas.style.cursor = this.defaultCursor;
  25179. }
  25180. }
  25181. if (pickResult) {
  25182. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25183. if (this.onPointerMove) {
  25184. this.onPointerMove(evt, pickResult, type);
  25185. }
  25186. if (this.onPointerObservable.hasObservers()) {
  25187. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25188. this._setRayOnPointerInfo(pi);
  25189. this.onPointerObservable.notifyObservers(pi, type);
  25190. }
  25191. }
  25192. return this;
  25193. };
  25194. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25195. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25196. if (pickResult) {
  25197. pi.ray = pickResult.ray;
  25198. }
  25199. this.onPrePointerObservable.notifyObservers(pi, type);
  25200. if (pi.skipOnPointerObservable) {
  25201. return true;
  25202. }
  25203. else {
  25204. return false;
  25205. }
  25206. };
  25207. /**
  25208. * Use this method to simulate a pointer down on a mesh
  25209. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25210. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25211. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25212. * @returns the current scene
  25213. */
  25214. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25215. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25216. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25217. return this;
  25218. }
  25219. return this._processPointerDown(pickResult, evt);
  25220. };
  25221. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25222. var _this = this;
  25223. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25224. this._pickedDownMesh = pickResult.pickedMesh;
  25225. var actionManager = pickResult.pickedMesh.actionManager;
  25226. if (actionManager) {
  25227. if (actionManager.hasPickTriggers) {
  25228. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25229. switch (evt.button) {
  25230. case 0:
  25231. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25232. break;
  25233. case 1:
  25234. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25235. break;
  25236. case 2:
  25237. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25238. break;
  25239. }
  25240. }
  25241. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25242. window.setTimeout(function () {
  25243. 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);
  25244. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25245. if (_this._totalPointersPressed !== 0 &&
  25246. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25247. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25248. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25249. _this._startingPointerTime = 0;
  25250. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25251. }
  25252. }
  25253. }, Scene.LongPressDelay);
  25254. }
  25255. }
  25256. }
  25257. if (pickResult) {
  25258. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25259. if (this.onPointerDown) {
  25260. this.onPointerDown(evt, pickResult, type);
  25261. }
  25262. if (this.onPointerObservable.hasObservers()) {
  25263. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25264. this._setRayOnPointerInfo(pi);
  25265. this.onPointerObservable.notifyObservers(pi, type);
  25266. }
  25267. }
  25268. return this;
  25269. };
  25270. /**
  25271. * Use this method to simulate a pointer up on a mesh
  25272. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25273. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25274. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25275. * @returns the current scene
  25276. */
  25277. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25278. var evt = new PointerEvent("pointerup", pointerEventInit);
  25279. var clickInfo = new ClickInfo();
  25280. clickInfo.singleClick = true;
  25281. clickInfo.ignore = true;
  25282. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25283. return this;
  25284. }
  25285. return this._processPointerUp(pickResult, evt, clickInfo);
  25286. };
  25287. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25288. if (pickResult && pickResult && pickResult.pickedMesh) {
  25289. this._pickedUpMesh = pickResult.pickedMesh;
  25290. if (this._pickedDownMesh === this._pickedUpMesh) {
  25291. if (this.onPointerPick) {
  25292. this.onPointerPick(evt, pickResult);
  25293. }
  25294. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25295. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25296. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25297. this._setRayOnPointerInfo(pi);
  25298. this.onPointerObservable.notifyObservers(pi, type_1);
  25299. }
  25300. }
  25301. if (pickResult.pickedMesh.actionManager) {
  25302. if (clickInfo.ignore) {
  25303. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25304. }
  25305. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25306. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25307. }
  25308. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25309. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25310. }
  25311. }
  25312. }
  25313. if (this._pickedDownMesh &&
  25314. this._pickedDownMesh.actionManager &&
  25315. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25316. this._pickedDownMesh !== this._pickedUpMesh) {
  25317. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25318. }
  25319. var type = BABYLON.PointerEventTypes.POINTERUP;
  25320. if (this.onPointerObservable.hasObservers()) {
  25321. if (!clickInfo.ignore) {
  25322. if (!clickInfo.hasSwiped) {
  25323. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25324. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25325. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25326. this._setRayOnPointerInfo(pi);
  25327. this.onPointerObservable.notifyObservers(pi, type_2);
  25328. }
  25329. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25330. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25331. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25332. this._setRayOnPointerInfo(pi);
  25333. this.onPointerObservable.notifyObservers(pi, type_3);
  25334. }
  25335. }
  25336. }
  25337. else {
  25338. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25339. this._setRayOnPointerInfo(pi);
  25340. this.onPointerObservable.notifyObservers(pi, type);
  25341. }
  25342. }
  25343. if (this.onPointerUp) {
  25344. this.onPointerUp(evt, pickResult, type);
  25345. }
  25346. return this;
  25347. };
  25348. /**
  25349. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25350. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25351. * @returns true if the pointer was captured
  25352. */
  25353. Scene.prototype.isPointerCaptured = function (pointerId) {
  25354. if (pointerId === void 0) { pointerId = 0; }
  25355. return this._pointerCaptures[pointerId];
  25356. };
  25357. /**
  25358. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25359. * @param attachUp defines if you want to attach events to pointerup
  25360. * @param attachDown defines if you want to attach events to pointerdown
  25361. * @param attachMove defines if you want to attach events to pointermove
  25362. */
  25363. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25364. var _this = this;
  25365. if (attachUp === void 0) { attachUp = true; }
  25366. if (attachDown === void 0) { attachDown = true; }
  25367. if (attachMove === void 0) { attachMove = true; }
  25368. this._initActionManager = function (act, clickInfo) {
  25369. if (!_this._meshPickProceed) {
  25370. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25371. _this._currentPickResult = pickResult;
  25372. if (pickResult) {
  25373. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25374. }
  25375. _this._meshPickProceed = true;
  25376. }
  25377. return act;
  25378. };
  25379. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25380. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25381. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25382. btn !== _this._previousButtonPressed) {
  25383. _this._doubleClickOccured = false;
  25384. clickInfo.singleClick = true;
  25385. clickInfo.ignore = false;
  25386. cb(clickInfo, _this._currentPickResult);
  25387. }
  25388. };
  25389. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25390. var clickInfo = new ClickInfo();
  25391. _this._currentPickResult = null;
  25392. var act = null;
  25393. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25394. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25395. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25396. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25397. act = _this._initActionManager(act, clickInfo);
  25398. if (act)
  25399. checkPicking = act.hasPickTriggers;
  25400. }
  25401. if (checkPicking) {
  25402. var btn = evt.button;
  25403. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25404. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25405. if (!clickInfo.hasSwiped) {
  25406. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25407. if (!checkSingleClickImmediately) {
  25408. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25409. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25410. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25411. act = _this._initActionManager(act, clickInfo);
  25412. if (act)
  25413. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25414. }
  25415. }
  25416. if (checkSingleClickImmediately) {
  25417. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25418. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25419. btn !== _this._previousButtonPressed) {
  25420. clickInfo.singleClick = true;
  25421. cb(clickInfo, _this._currentPickResult);
  25422. }
  25423. }
  25424. // at least one double click is required to be check and exclusive double click is enabled
  25425. else {
  25426. // wait that no double click has been raised during the double click delay
  25427. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25428. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25429. }
  25430. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25431. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25432. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25433. act = _this._initActionManager(act, clickInfo);
  25434. if (act)
  25435. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25436. }
  25437. if (checkDoubleClick) {
  25438. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25439. if (btn === _this._previousButtonPressed &&
  25440. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25441. !_this._doubleClickOccured) {
  25442. // pointer has not moved for 2 clicks, it's a double click
  25443. if (!clickInfo.hasSwiped &&
  25444. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25445. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25446. _this._previousStartingPointerTime = 0;
  25447. _this._doubleClickOccured = true;
  25448. clickInfo.doubleClick = true;
  25449. clickInfo.ignore = false;
  25450. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25451. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25452. }
  25453. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25454. cb(clickInfo, _this._currentPickResult);
  25455. }
  25456. // if the two successive clicks are too far, it's just two simple clicks
  25457. else {
  25458. _this._doubleClickOccured = false;
  25459. _this._previousStartingPointerTime = _this._startingPointerTime;
  25460. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25461. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25462. _this._previousButtonPressed = btn;
  25463. if (Scene.ExclusiveDoubleClickMode) {
  25464. if (_this._previousDelayedSimpleClickTimeout) {
  25465. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25466. }
  25467. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25468. cb(clickInfo, _this._previousPickResult);
  25469. }
  25470. else {
  25471. cb(clickInfo, _this._currentPickResult);
  25472. }
  25473. }
  25474. }
  25475. // just the first click of the double has been raised
  25476. else {
  25477. _this._doubleClickOccured = false;
  25478. _this._previousStartingPointerTime = _this._startingPointerTime;
  25479. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25480. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25481. _this._previousButtonPressed = btn;
  25482. }
  25483. }
  25484. }
  25485. }
  25486. clickInfo.ignore = true;
  25487. cb(clickInfo, _this._currentPickResult);
  25488. };
  25489. this._spritePredicate = function (sprite) {
  25490. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25491. };
  25492. this._onPointerMove = function (evt) {
  25493. _this._updatePointerPosition(evt);
  25494. // PreObservable support
  25495. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25496. return;
  25497. }
  25498. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25499. return;
  25500. }
  25501. if (!_this.pointerMovePredicate) {
  25502. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25503. }
  25504. // Meshes
  25505. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25506. _this._processPointerMove(pickResult, evt);
  25507. };
  25508. this._onPointerDown = function (evt) {
  25509. _this._totalPointersPressed++;
  25510. _this._pickedDownMesh = null;
  25511. _this._meshPickProceed = false;
  25512. _this._updatePointerPosition(evt);
  25513. if (_this.preventDefaultOnPointerDown && canvas) {
  25514. evt.preventDefault();
  25515. canvas.focus();
  25516. }
  25517. // PreObservable support
  25518. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25519. return;
  25520. }
  25521. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25522. return;
  25523. }
  25524. _this._pointerCaptures[evt.pointerId] = true;
  25525. _this._startingPointerPosition.x = _this._pointerX;
  25526. _this._startingPointerPosition.y = _this._pointerY;
  25527. _this._startingPointerTime = Date.now();
  25528. if (!_this.pointerDownPredicate) {
  25529. _this.pointerDownPredicate = function (mesh) {
  25530. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25531. };
  25532. }
  25533. // Meshes
  25534. _this._pickedDownMesh = null;
  25535. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25536. _this._processPointerDown(pickResult, evt);
  25537. // Sprites
  25538. _this._pickedDownSprite = null;
  25539. if (_this.spriteManagers.length > 0) {
  25540. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25541. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25542. if (pickResult.pickedSprite.actionManager) {
  25543. _this._pickedDownSprite = pickResult.pickedSprite;
  25544. switch (evt.button) {
  25545. case 0:
  25546. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25547. break;
  25548. case 1:
  25549. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25550. break;
  25551. case 2:
  25552. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25553. break;
  25554. }
  25555. if (pickResult.pickedSprite.actionManager) {
  25556. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25557. }
  25558. }
  25559. }
  25560. }
  25561. };
  25562. this._onPointerUp = function (evt) {
  25563. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25564. return; // So we need to test it the pointer down was pressed before.
  25565. }
  25566. _this._totalPointersPressed--;
  25567. _this._pickedUpMesh = null;
  25568. _this._meshPickProceed = false;
  25569. _this._updatePointerPosition(evt);
  25570. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25571. // PreObservable support
  25572. if (_this.onPrePointerObservable.hasObservers()) {
  25573. if (!clickInfo.ignore) {
  25574. if (!clickInfo.hasSwiped) {
  25575. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25576. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25577. return;
  25578. }
  25579. }
  25580. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25581. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25582. return;
  25583. }
  25584. }
  25585. }
  25586. }
  25587. else {
  25588. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25589. return;
  25590. }
  25591. }
  25592. }
  25593. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25594. return;
  25595. }
  25596. _this._pointerCaptures[evt.pointerId] = false;
  25597. if (!_this.pointerUpPredicate) {
  25598. _this.pointerUpPredicate = function (mesh) {
  25599. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25600. };
  25601. }
  25602. // Meshes
  25603. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25604. _this._initActionManager(null, clickInfo);
  25605. }
  25606. if (!pickResult) {
  25607. pickResult = _this._currentPickResult;
  25608. }
  25609. _this._processPointerUp(pickResult, evt, clickInfo);
  25610. // Sprites
  25611. if (!clickInfo.ignore) {
  25612. if (_this.spriteManagers.length > 0) {
  25613. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25614. if (spritePickResult) {
  25615. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25616. if (spritePickResult.pickedSprite.actionManager) {
  25617. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25618. if (spritePickResult.pickedSprite.actionManager) {
  25619. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25620. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25621. }
  25622. }
  25623. }
  25624. }
  25625. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25626. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25627. }
  25628. }
  25629. }
  25630. }
  25631. _this._previousPickResult = _this._currentPickResult;
  25632. });
  25633. };
  25634. this._onKeyDown = function (evt) {
  25635. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25636. if (_this.onPreKeyboardObservable.hasObservers()) {
  25637. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25638. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25639. if (pi.skipOnPointerObservable) {
  25640. return;
  25641. }
  25642. }
  25643. if (_this.onKeyboardObservable.hasObservers()) {
  25644. var pi = new BABYLON.KeyboardInfo(type, evt);
  25645. _this.onKeyboardObservable.notifyObservers(pi, type);
  25646. }
  25647. if (_this.actionManager) {
  25648. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25649. }
  25650. };
  25651. this._onKeyUp = function (evt) {
  25652. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25653. if (_this.onPreKeyboardObservable.hasObservers()) {
  25654. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25655. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25656. if (pi.skipOnPointerObservable) {
  25657. return;
  25658. }
  25659. }
  25660. if (_this.onKeyboardObservable.hasObservers()) {
  25661. var pi = new BABYLON.KeyboardInfo(type, evt);
  25662. _this.onKeyboardObservable.notifyObservers(pi, type);
  25663. }
  25664. if (_this.actionManager) {
  25665. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25666. }
  25667. };
  25668. var engine = this.getEngine();
  25669. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25670. if (!canvas) {
  25671. return;
  25672. }
  25673. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25674. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25675. });
  25676. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25677. if (!canvas) {
  25678. return;
  25679. }
  25680. canvas.removeEventListener("keydown", _this._onKeyDown);
  25681. canvas.removeEventListener("keyup", _this._onKeyUp);
  25682. });
  25683. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25684. var canvas = this._engine.getRenderingCanvas();
  25685. if (!canvas) {
  25686. return;
  25687. }
  25688. if (attachMove) {
  25689. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25690. // Wheel
  25691. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25692. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25693. }
  25694. if (attachDown) {
  25695. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25696. }
  25697. if (attachUp) {
  25698. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25699. }
  25700. canvas.tabIndex = 1;
  25701. };
  25702. /** Detaches all event handlers*/
  25703. Scene.prototype.detachControl = function () {
  25704. var engine = this.getEngine();
  25705. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25706. var canvas = engine.getRenderingCanvas();
  25707. if (!canvas) {
  25708. return;
  25709. }
  25710. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25711. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25712. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25713. if (this._onCanvasBlurObserver) {
  25714. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25715. }
  25716. if (this._onCanvasFocusObserver) {
  25717. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25718. }
  25719. // Wheel
  25720. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25721. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25722. // Keyboard
  25723. canvas.removeEventListener("keydown", this._onKeyDown);
  25724. canvas.removeEventListener("keyup", this._onKeyUp);
  25725. // Observables
  25726. this.onKeyboardObservable.clear();
  25727. this.onPreKeyboardObservable.clear();
  25728. this.onPointerObservable.clear();
  25729. this.onPrePointerObservable.clear();
  25730. };
  25731. /**
  25732. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25733. * Delay loaded resources are not taking in account
  25734. * @return true if all required resources are ready
  25735. */
  25736. Scene.prototype.isReady = function () {
  25737. if (this._isDisposed) {
  25738. return false;
  25739. }
  25740. if (this._pendingData.length > 0) {
  25741. return false;
  25742. }
  25743. var index;
  25744. var engine = this.getEngine();
  25745. // Geometries
  25746. for (index = 0; index < this._geometries.length; index++) {
  25747. var geometry = this._geometries[index];
  25748. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25749. return false;
  25750. }
  25751. }
  25752. // Meshes
  25753. for (index = 0; index < this.meshes.length; index++) {
  25754. var mesh = this.meshes[index];
  25755. if (!mesh.isEnabled()) {
  25756. continue;
  25757. }
  25758. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25759. continue;
  25760. }
  25761. if (!mesh.isReady(true)) {
  25762. return false;
  25763. }
  25764. // Effect layers
  25765. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25766. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25767. var layer = _a[_i];
  25768. if (!layer.hasMesh(mesh)) {
  25769. continue;
  25770. }
  25771. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25772. var subMesh = _c[_b];
  25773. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25774. return false;
  25775. }
  25776. }
  25777. }
  25778. }
  25779. // Post-processes
  25780. if (this.activeCameras && this.activeCameras.length > 0) {
  25781. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25782. var camera = _e[_d];
  25783. if (!camera.isReady(true)) {
  25784. return false;
  25785. }
  25786. }
  25787. }
  25788. else if (this.activeCamera) {
  25789. if (!this.activeCamera.isReady(true)) {
  25790. return false;
  25791. }
  25792. }
  25793. // Particles
  25794. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25795. var particleSystem = _g[_f];
  25796. if (!particleSystem.isReady()) {
  25797. return false;
  25798. }
  25799. }
  25800. return true;
  25801. };
  25802. /** Resets all cached information relative to material (including effect and visibility) */
  25803. Scene.prototype.resetCachedMaterial = function () {
  25804. this._cachedMaterial = null;
  25805. this._cachedEffect = null;
  25806. this._cachedVisibility = null;
  25807. };
  25808. /**
  25809. * Registers a function to be called before every frame render
  25810. * @param func defines the function to register
  25811. */
  25812. Scene.prototype.registerBeforeRender = function (func) {
  25813. this.onBeforeRenderObservable.add(func);
  25814. };
  25815. /**
  25816. * Unregisters a function called before every frame render
  25817. * @param func defines the function to unregister
  25818. */
  25819. Scene.prototype.unregisterBeforeRender = function (func) {
  25820. this.onBeforeRenderObservable.removeCallback(func);
  25821. };
  25822. /**
  25823. * Registers a function to be called after every frame render
  25824. * @param func defines the function to register
  25825. */
  25826. Scene.prototype.registerAfterRender = function (func) {
  25827. this.onAfterRenderObservable.add(func);
  25828. };
  25829. /**
  25830. * Unregisters a function called after every frame render
  25831. * @param func defines the function to unregister
  25832. */
  25833. Scene.prototype.unregisterAfterRender = function (func) {
  25834. this.onAfterRenderObservable.removeCallback(func);
  25835. };
  25836. Scene.prototype._executeOnceBeforeRender = function (func) {
  25837. var _this = this;
  25838. var execFunc = function () {
  25839. func();
  25840. setTimeout(function () {
  25841. _this.unregisterBeforeRender(execFunc);
  25842. });
  25843. };
  25844. this.registerBeforeRender(execFunc);
  25845. };
  25846. /**
  25847. * The provided function will run before render once and will be disposed afterwards.
  25848. * A timeout delay can be provided so that the function will be executed in N ms.
  25849. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25850. * @param func The function to be executed.
  25851. * @param timeout optional delay in ms
  25852. */
  25853. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25854. var _this = this;
  25855. if (timeout !== undefined) {
  25856. setTimeout(function () {
  25857. _this._executeOnceBeforeRender(func);
  25858. }, timeout);
  25859. }
  25860. else {
  25861. this._executeOnceBeforeRender(func);
  25862. }
  25863. };
  25864. /** @hidden */
  25865. Scene.prototype._addPendingData = function (data) {
  25866. this._pendingData.push(data);
  25867. };
  25868. /** @hidden */
  25869. Scene.prototype._removePendingData = function (data) {
  25870. var wasLoading = this.isLoading;
  25871. var index = this._pendingData.indexOf(data);
  25872. if (index !== -1) {
  25873. this._pendingData.splice(index, 1);
  25874. }
  25875. if (wasLoading && !this.isLoading) {
  25876. this.onDataLoadedObservable.notifyObservers(this);
  25877. }
  25878. };
  25879. /**
  25880. * Returns the number of items waiting to be loaded
  25881. * @returns the number of items waiting to be loaded
  25882. */
  25883. Scene.prototype.getWaitingItemsCount = function () {
  25884. return this._pendingData.length;
  25885. };
  25886. Object.defineProperty(Scene.prototype, "isLoading", {
  25887. /**
  25888. * Returns a boolean indicating if the scene is still loading data
  25889. */
  25890. get: function () {
  25891. return this._pendingData.length > 0;
  25892. },
  25893. enumerable: true,
  25894. configurable: true
  25895. });
  25896. /**
  25897. * Registers a function to be executed when the scene is ready
  25898. * @param {Function} func - the function to be executed
  25899. */
  25900. Scene.prototype.executeWhenReady = function (func) {
  25901. var _this = this;
  25902. this.onReadyObservable.add(func);
  25903. if (this._executeWhenReadyTimeoutId !== -1) {
  25904. return;
  25905. }
  25906. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25907. _this._checkIsReady();
  25908. }, 150);
  25909. };
  25910. /**
  25911. * Returns a promise that resolves when the scene is ready
  25912. * @returns A promise that resolves when the scene is ready
  25913. */
  25914. Scene.prototype.whenReadyAsync = function () {
  25915. var _this = this;
  25916. return new Promise(function (resolve) {
  25917. _this.executeWhenReady(function () {
  25918. resolve();
  25919. });
  25920. });
  25921. };
  25922. /** @hidden */
  25923. Scene.prototype._checkIsReady = function () {
  25924. var _this = this;
  25925. if (this.isReady()) {
  25926. this.onReadyObservable.notifyObservers(this);
  25927. this.onReadyObservable.clear();
  25928. this._executeWhenReadyTimeoutId = -1;
  25929. return;
  25930. }
  25931. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25932. _this._checkIsReady();
  25933. }, 150);
  25934. };
  25935. // Animations
  25936. /**
  25937. * Will start the animation sequence of a given target
  25938. * @param target defines the target
  25939. * @param from defines from which frame should animation start
  25940. * @param to defines until which frame should animation run.
  25941. * @param weight defines the weight to apply to the animation (1.0 by default)
  25942. * @param loop defines if the animation loops
  25943. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25944. * @param onAnimationEnd defines the function to be executed when the animation ends
  25945. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25946. * @returns the animatable object created for this animation
  25947. */
  25948. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25949. if (weight === void 0) { weight = 1.0; }
  25950. if (speedRatio === void 0) { speedRatio = 1.0; }
  25951. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25952. returnedAnimatable.weight = weight;
  25953. return returnedAnimatable;
  25954. };
  25955. /**
  25956. * Will start the animation sequence of a given target
  25957. * @param target defines the target
  25958. * @param from defines from which frame should animation start
  25959. * @param to defines until which frame should animation run.
  25960. * @param loop defines if the animation loops
  25961. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25962. * @param onAnimationEnd defines the function to be executed when the animation ends
  25963. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25964. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25965. * @returns the animatable object created for this animation
  25966. */
  25967. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25968. if (speedRatio === void 0) { speedRatio = 1.0; }
  25969. if (stopCurrent === void 0) { stopCurrent = true; }
  25970. if (from > to && speedRatio > 0) {
  25971. speedRatio *= -1;
  25972. }
  25973. if (stopCurrent) {
  25974. this.stopAnimation(target);
  25975. }
  25976. if (!animatable) {
  25977. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25978. }
  25979. // Local animations
  25980. if (target.animations) {
  25981. animatable.appendAnimations(target, target.animations);
  25982. }
  25983. // Children animations
  25984. if (target.getAnimatables) {
  25985. var animatables = target.getAnimatables();
  25986. for (var index = 0; index < animatables.length; index++) {
  25987. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25988. }
  25989. }
  25990. animatable.reset();
  25991. return animatable;
  25992. };
  25993. /**
  25994. * Begin a new animation on a given node
  25995. * @param target defines the target where the animation will take place
  25996. * @param animations defines the list of animations to start
  25997. * @param from defines the initial value
  25998. * @param to defines the final value
  25999. * @param loop defines if you want animation to loop (off by default)
  26000. * @param speedRatio defines the speed ratio to apply to all animations
  26001. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26002. * @returns the list of created animatables
  26003. */
  26004. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26005. if (speedRatio === undefined) {
  26006. speedRatio = 1.0;
  26007. }
  26008. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26009. return animatable;
  26010. };
  26011. /**
  26012. * Begin a new animation on a given node and its hierarchy
  26013. * @param target defines the root node where the animation will take place
  26014. * @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.
  26015. * @param animations defines the list of animations to start
  26016. * @param from defines the initial value
  26017. * @param to defines the final value
  26018. * @param loop defines if you want animation to loop (off by default)
  26019. * @param speedRatio defines the speed ratio to apply to all animations
  26020. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26021. * @returns the list of animatables created for all nodes
  26022. */
  26023. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26024. var children = target.getDescendants(directDescendantsOnly);
  26025. var result = [];
  26026. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26027. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26028. var child = children_1[_i];
  26029. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26030. }
  26031. return result;
  26032. };
  26033. /**
  26034. * Gets the animatable associated with a specific target
  26035. * @param target defines the target of the animatable
  26036. * @returns the required animatable if found
  26037. */
  26038. Scene.prototype.getAnimatableByTarget = function (target) {
  26039. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26040. if (this._activeAnimatables[index].target === target) {
  26041. return this._activeAnimatables[index];
  26042. }
  26043. }
  26044. return null;
  26045. };
  26046. /**
  26047. * Gets all animatables associated with a given target
  26048. * @param target defines the target to look animatables for
  26049. * @returns an array of Animatables
  26050. */
  26051. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26052. var result = [];
  26053. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26054. if (this._activeAnimatables[index].target === target) {
  26055. result.push(this._activeAnimatables[index]);
  26056. }
  26057. }
  26058. return result;
  26059. };
  26060. Object.defineProperty(Scene.prototype, "animatables", {
  26061. /**
  26062. * Gets all animatable attached to the scene
  26063. */
  26064. get: function () {
  26065. return this._activeAnimatables;
  26066. },
  26067. enumerable: true,
  26068. configurable: true
  26069. });
  26070. /**
  26071. * Will stop the animation of the given target
  26072. * @param target - the target
  26073. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26074. */
  26075. Scene.prototype.stopAnimation = function (target, animationName) {
  26076. var animatables = this.getAllAnimatablesByTarget(target);
  26077. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26078. var animatable = animatables_1[_i];
  26079. animatable.stop(animationName);
  26080. }
  26081. };
  26082. /**
  26083. * Stops and removes all animations that have been applied to the scene
  26084. */
  26085. Scene.prototype.stopAllAnimations = function () {
  26086. if (this._activeAnimatables) {
  26087. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26088. this._activeAnimatables[i].stop();
  26089. }
  26090. this._activeAnimatables = [];
  26091. }
  26092. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26093. var group = _a[_i];
  26094. group.stop();
  26095. }
  26096. };
  26097. Scene.prototype._animate = function () {
  26098. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26099. return;
  26100. }
  26101. // Getting time
  26102. var now = BABYLON.Tools.Now;
  26103. if (!this._animationTimeLast) {
  26104. if (this._pendingData.length > 0) {
  26105. return;
  26106. }
  26107. this._animationTimeLast = now;
  26108. }
  26109. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26110. this._animationTime += deltaTime;
  26111. this._animationTimeLast = now;
  26112. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26113. this._activeAnimatables[index]._animate(this._animationTime);
  26114. }
  26115. // Late animation bindings
  26116. this._processLateAnimationBindings();
  26117. };
  26118. /** @hidden */
  26119. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26120. var target = runtimeAnimation.target;
  26121. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26122. if (!target._lateAnimationHolders) {
  26123. target._lateAnimationHolders = {};
  26124. }
  26125. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26126. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26127. totalWeight: 0,
  26128. animations: [],
  26129. originalValue: originalValue
  26130. };
  26131. }
  26132. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26133. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26134. };
  26135. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26136. var normalizer = 1.0;
  26137. var finalPosition = BABYLON.Tmp.Vector3[0];
  26138. var finalScaling = BABYLON.Tmp.Vector3[1];
  26139. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26140. var startIndex = 0;
  26141. var originalAnimation = holder.animations[0];
  26142. var originalValue = holder.originalValue;
  26143. var scale = 1;
  26144. if (holder.totalWeight < 1.0) {
  26145. // We need to mix the original value in
  26146. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26147. scale = 1.0 - holder.totalWeight;
  26148. }
  26149. else {
  26150. startIndex = 1;
  26151. // We need to normalize the weights
  26152. normalizer = holder.totalWeight;
  26153. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26154. scale = originalAnimation.weight / normalizer;
  26155. if (scale == 1) {
  26156. return originalAnimation.currentValue;
  26157. }
  26158. }
  26159. finalScaling.scaleInPlace(scale);
  26160. finalPosition.scaleInPlace(scale);
  26161. finalQuaternion.scaleInPlace(scale);
  26162. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26163. var runtimeAnimation = holder.animations[animIndex];
  26164. var scale = runtimeAnimation.weight / normalizer;
  26165. var currentPosition = BABYLON.Tmp.Vector3[2];
  26166. var currentScaling = BABYLON.Tmp.Vector3[3];
  26167. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26168. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26169. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26170. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26171. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26172. }
  26173. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26174. return originalAnimation._workValue;
  26175. };
  26176. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26177. var originalAnimation = holder.animations[0];
  26178. var originalValue = holder.originalValue;
  26179. if (holder.animations.length === 1) {
  26180. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26181. }
  26182. var normalizer = 1.0;
  26183. var quaternions;
  26184. var weights;
  26185. if (holder.totalWeight < 1.0) {
  26186. var scale = 1.0 - holder.totalWeight;
  26187. quaternions = [];
  26188. weights = [];
  26189. quaternions.push(originalValue);
  26190. weights.push(scale);
  26191. }
  26192. else {
  26193. if (holder.animations.length === 2) { // Slerp as soon as we can
  26194. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26195. }
  26196. quaternions = [];
  26197. weights = [];
  26198. normalizer = holder.totalWeight;
  26199. }
  26200. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26201. var runtimeAnimation = holder.animations[animIndex];
  26202. quaternions.push(runtimeAnimation.currentValue);
  26203. weights.push(runtimeAnimation.weight / normalizer);
  26204. }
  26205. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26206. var cumulativeAmount = 0;
  26207. var cumulativeQuaternion = null;
  26208. for (var index = 0; index < quaternions.length;) {
  26209. if (!cumulativeQuaternion) {
  26210. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26211. cumulativeAmount = weights[index] + weights[index + 1];
  26212. index += 2;
  26213. continue;
  26214. }
  26215. cumulativeAmount += weights[index];
  26216. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26217. index++;
  26218. }
  26219. return cumulativeQuaternion;
  26220. };
  26221. Scene.prototype._processLateAnimationBindings = function () {
  26222. if (!this._registeredForLateAnimationBindings.length) {
  26223. return;
  26224. }
  26225. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26226. var target = this._registeredForLateAnimationBindings.data[index];
  26227. for (var path in target._lateAnimationHolders) {
  26228. var holder = target._lateAnimationHolders[path];
  26229. var originalAnimation = holder.animations[0];
  26230. var originalValue = holder.originalValue;
  26231. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26232. var finalValue = void 0;
  26233. if (matrixDecomposeMode) {
  26234. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26235. }
  26236. else {
  26237. var quaternionMode = originalValue.w !== undefined;
  26238. if (quaternionMode) {
  26239. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26240. }
  26241. else {
  26242. var startIndex = 0;
  26243. var normalizer = 1.0;
  26244. if (holder.totalWeight < 1.0) {
  26245. // We need to mix the original value in
  26246. if (originalValue.scale) {
  26247. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26248. }
  26249. else {
  26250. finalValue = originalValue * (1.0 - holder.totalWeight);
  26251. }
  26252. }
  26253. else {
  26254. // We need to normalize the weights
  26255. normalizer = holder.totalWeight;
  26256. var scale_1 = originalAnimation.weight / normalizer;
  26257. if (scale_1 !== 1) {
  26258. if (originalAnimation.currentValue.scale) {
  26259. finalValue = originalAnimation.currentValue.scale(scale_1);
  26260. }
  26261. else {
  26262. finalValue = originalAnimation.currentValue * scale_1;
  26263. }
  26264. }
  26265. else {
  26266. finalValue = originalAnimation.currentValue;
  26267. }
  26268. startIndex = 1;
  26269. }
  26270. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26271. var runtimeAnimation = holder.animations[animIndex];
  26272. var scale = runtimeAnimation.weight / normalizer;
  26273. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26274. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26275. }
  26276. else {
  26277. finalValue += runtimeAnimation.currentValue * scale;
  26278. }
  26279. }
  26280. }
  26281. }
  26282. target[path] = finalValue;
  26283. }
  26284. target._lateAnimationHolders = {};
  26285. }
  26286. this._registeredForLateAnimationBindings.reset();
  26287. };
  26288. // Matrix
  26289. /** @hidden */
  26290. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26291. this._useAlternateCameraConfiguration = active;
  26292. };
  26293. /**
  26294. * Gets the current view matrix
  26295. * @returns a Matrix
  26296. */
  26297. Scene.prototype.getViewMatrix = function () {
  26298. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26299. };
  26300. /**
  26301. * Gets the current projection matrix
  26302. * @returns a Matrix
  26303. */
  26304. Scene.prototype.getProjectionMatrix = function () {
  26305. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26306. };
  26307. /**
  26308. * Gets the current transform matrix
  26309. * @returns a Matrix made of View * Projection
  26310. */
  26311. Scene.prototype.getTransformMatrix = function () {
  26312. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26313. };
  26314. /**
  26315. * Sets the current transform matrix
  26316. * @param view defines the View matrix to use
  26317. * @param projection defines the Projection matrix to use
  26318. */
  26319. Scene.prototype.setTransformMatrix = function (view, projection) {
  26320. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26321. return;
  26322. }
  26323. this._viewUpdateFlag = view.updateFlag;
  26324. this._projectionUpdateFlag = projection.updateFlag;
  26325. this._viewMatrix = view;
  26326. this._projectionMatrix = projection;
  26327. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26328. // Update frustum
  26329. if (!this._frustumPlanes) {
  26330. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26331. }
  26332. else {
  26333. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26334. }
  26335. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26336. var otherCamera = this.activeCamera._alternateCamera;
  26337. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26338. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26339. }
  26340. if (this._sceneUbo.useUbo) {
  26341. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26342. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26343. this._sceneUbo.update();
  26344. }
  26345. };
  26346. /** @hidden */
  26347. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26348. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26349. return;
  26350. }
  26351. this._alternateViewUpdateFlag = view.updateFlag;
  26352. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26353. this._alternateViewMatrix = view;
  26354. this._alternateProjectionMatrix = projection;
  26355. if (!this._alternateTransformMatrix) {
  26356. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26357. }
  26358. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26359. if (!this._alternateSceneUbo) {
  26360. this._createAlternateUbo();
  26361. }
  26362. if (this._alternateSceneUbo.useUbo) {
  26363. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26364. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26365. this._alternateSceneUbo.update();
  26366. }
  26367. };
  26368. /**
  26369. * Gets the uniform buffer used to store scene data
  26370. * @returns a UniformBuffer
  26371. */
  26372. Scene.prototype.getSceneUniformBuffer = function () {
  26373. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26374. };
  26375. /**
  26376. * Gets an unique (relatively to the current scene) Id
  26377. * @returns an unique number for the scene
  26378. */
  26379. Scene.prototype.getUniqueId = function () {
  26380. var result = Scene._uniqueIdCounter;
  26381. Scene._uniqueIdCounter++;
  26382. return result;
  26383. };
  26384. /**
  26385. * Add a mesh to the list of scene's meshes
  26386. * @param newMesh defines the mesh to add
  26387. * @param recursive if all child meshes should also be added to the scene
  26388. */
  26389. Scene.prototype.addMesh = function (newMesh, recursive) {
  26390. var _this = this;
  26391. if (recursive === void 0) { recursive = false; }
  26392. this.meshes.push(newMesh);
  26393. //notify the collision coordinator
  26394. if (this.collisionCoordinator) {
  26395. this.collisionCoordinator.onMeshAdded(newMesh);
  26396. }
  26397. newMesh._resyncLightSources();
  26398. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26399. if (recursive) {
  26400. newMesh.getChildMeshes().forEach(function (m) {
  26401. _this.addMesh(m);
  26402. });
  26403. }
  26404. };
  26405. /**
  26406. * Remove a mesh for the list of scene's meshes
  26407. * @param toRemove defines the mesh to remove
  26408. * @param recursive if all child meshes should also be removed from the scene
  26409. * @returns the index where the mesh was in the mesh list
  26410. */
  26411. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26412. var _this = this;
  26413. if (recursive === void 0) { recursive = false; }
  26414. var index = this.meshes.indexOf(toRemove);
  26415. if (index !== -1) {
  26416. // Remove from the scene if mesh found
  26417. this.meshes.splice(index, 1);
  26418. }
  26419. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26420. if (recursive) {
  26421. toRemove.getChildMeshes().forEach(function (m) {
  26422. _this.removeMesh(m);
  26423. });
  26424. }
  26425. return index;
  26426. };
  26427. /**
  26428. * Add a transform node to the list of scene's transform nodes
  26429. * @param newTransformNode defines the transform node to add
  26430. */
  26431. Scene.prototype.addTransformNode = function (newTransformNode) {
  26432. this.transformNodes.push(newTransformNode);
  26433. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26434. };
  26435. /**
  26436. * Remove a transform node for the list of scene's transform nodes
  26437. * @param toRemove defines the transform node to remove
  26438. * @returns the index where the transform node was in the transform node list
  26439. */
  26440. Scene.prototype.removeTransformNode = function (toRemove) {
  26441. var index = this.transformNodes.indexOf(toRemove);
  26442. if (index !== -1) {
  26443. // Remove from the scene if found
  26444. this.transformNodes.splice(index, 1);
  26445. }
  26446. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26447. return index;
  26448. };
  26449. /**
  26450. * Remove a skeleton for the list of scene's skeletons
  26451. * @param toRemove defines the skeleton to remove
  26452. * @returns the index where the skeleton was in the skeleton list
  26453. */
  26454. Scene.prototype.removeSkeleton = function (toRemove) {
  26455. var index = this.skeletons.indexOf(toRemove);
  26456. if (index !== -1) {
  26457. // Remove from the scene if found
  26458. this.skeletons.splice(index, 1);
  26459. }
  26460. return index;
  26461. };
  26462. /**
  26463. * Remove a morph target for the list of scene's morph targets
  26464. * @param toRemove defines the morph target to remove
  26465. * @returns the index where the morph target was in the morph target list
  26466. */
  26467. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26468. var index = this.morphTargetManagers.indexOf(toRemove);
  26469. if (index !== -1) {
  26470. // Remove from the scene if found
  26471. this.morphTargetManagers.splice(index, 1);
  26472. }
  26473. return index;
  26474. };
  26475. /**
  26476. * Remove a light for the list of scene's lights
  26477. * @param toRemove defines the light to remove
  26478. * @returns the index where the light was in the light list
  26479. */
  26480. Scene.prototype.removeLight = function (toRemove) {
  26481. var index = this.lights.indexOf(toRemove);
  26482. if (index !== -1) {
  26483. // Remove from meshes
  26484. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26485. var mesh = _a[_i];
  26486. mesh._removeLightSource(toRemove);
  26487. }
  26488. // Remove from the scene if mesh found
  26489. this.lights.splice(index, 1);
  26490. this.sortLightsByPriority();
  26491. }
  26492. this.onLightRemovedObservable.notifyObservers(toRemove);
  26493. return index;
  26494. };
  26495. /**
  26496. * Remove a camera for the list of scene's cameras
  26497. * @param toRemove defines the camera to remove
  26498. * @returns the index where the camera was in the camera list
  26499. */
  26500. Scene.prototype.removeCamera = function (toRemove) {
  26501. var index = this.cameras.indexOf(toRemove);
  26502. if (index !== -1) {
  26503. // Remove from the scene if mesh found
  26504. this.cameras.splice(index, 1);
  26505. }
  26506. // Remove from activeCameras
  26507. var index2 = this.activeCameras.indexOf(toRemove);
  26508. if (index2 !== -1) {
  26509. // Remove from the scene if mesh found
  26510. this.activeCameras.splice(index2, 1);
  26511. }
  26512. // Reset the activeCamera
  26513. if (this.activeCamera === toRemove) {
  26514. if (this.cameras.length > 0) {
  26515. this.activeCamera = this.cameras[0];
  26516. }
  26517. else {
  26518. this.activeCamera = null;
  26519. }
  26520. }
  26521. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26522. return index;
  26523. };
  26524. /**
  26525. * Remove a particle system for the list of scene's particle systems
  26526. * @param toRemove defines the particle system to remove
  26527. * @returns the index where the particle system was in the particle system list
  26528. */
  26529. Scene.prototype.removeParticleSystem = function (toRemove) {
  26530. var index = this.particleSystems.indexOf(toRemove);
  26531. if (index !== -1) {
  26532. this.particleSystems.splice(index, 1);
  26533. }
  26534. return index;
  26535. };
  26536. /**
  26537. * Remove a animation for the list of scene's animations
  26538. * @param toRemove defines the animation to remove
  26539. * @returns the index where the animation was in the animation list
  26540. */
  26541. Scene.prototype.removeAnimation = function (toRemove) {
  26542. var index = this.animations.indexOf(toRemove);
  26543. if (index !== -1) {
  26544. this.animations.splice(index, 1);
  26545. }
  26546. return index;
  26547. };
  26548. /**
  26549. * Removes the given animation group from this scene.
  26550. * @param toRemove The animation group to remove
  26551. * @returns The index of the removed animation group
  26552. */
  26553. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26554. var index = this.animationGroups.indexOf(toRemove);
  26555. if (index !== -1) {
  26556. this.animationGroups.splice(index, 1);
  26557. }
  26558. return index;
  26559. };
  26560. /**
  26561. * Removes the given multi-material from this scene.
  26562. * @param toRemove The multi-material to remove
  26563. * @returns The index of the removed multi-material
  26564. */
  26565. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26566. var index = this.multiMaterials.indexOf(toRemove);
  26567. if (index !== -1) {
  26568. this.multiMaterials.splice(index, 1);
  26569. }
  26570. return index;
  26571. };
  26572. /**
  26573. * Removes the given material from this scene.
  26574. * @param toRemove The material to remove
  26575. * @returns The index of the removed material
  26576. */
  26577. Scene.prototype.removeMaterial = function (toRemove) {
  26578. var index = this.materials.indexOf(toRemove);
  26579. if (index !== -1) {
  26580. this.materials.splice(index, 1);
  26581. }
  26582. return index;
  26583. };
  26584. /**
  26585. * Removes the given lens flare system from this scene.
  26586. * @param toRemove The lens flare system to remove
  26587. * @returns The index of the removed lens flare system
  26588. */
  26589. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26590. var index = this.lensFlareSystems.indexOf(toRemove);
  26591. if (index !== -1) {
  26592. this.lensFlareSystems.splice(index, 1);
  26593. }
  26594. return index;
  26595. };
  26596. /**
  26597. * Removes the given action manager from this scene.
  26598. * @param toRemove The action manager to remove
  26599. * @returns The index of the removed action manager
  26600. */
  26601. Scene.prototype.removeActionManager = function (toRemove) {
  26602. var index = this._actionManagers.indexOf(toRemove);
  26603. if (index !== -1) {
  26604. this._actionManagers.splice(index, 1);
  26605. }
  26606. return index;
  26607. };
  26608. /**
  26609. * Removes the given effect layer from this scene.
  26610. * @param toRemove defines the effect layer to remove
  26611. * @returns the index of the removed effect layer
  26612. */
  26613. Scene.prototype.removeEffectLayer = function (toRemove) {
  26614. var index = this.effectLayers.indexOf(toRemove);
  26615. if (index !== -1) {
  26616. this.effectLayers.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 lens flare system to this scene
  26723. * @param newLensFlareSystem The lens flare system to add
  26724. */
  26725. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26726. this.lensFlareSystems.push(newLensFlareSystem);
  26727. };
  26728. /**
  26729. * Adds the given effect layer to this scene
  26730. * @param newEffectLayer defines the effect layer to add
  26731. */
  26732. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26733. this.effectLayers.push(newEffectLayer);
  26734. };
  26735. /**
  26736. * Adds the given action manager to this scene
  26737. * @param newActionManager The action manager to add
  26738. */
  26739. Scene.prototype.addActionManager = function (newActionManager) {
  26740. this._actionManagers.push(newActionManager);
  26741. };
  26742. /**
  26743. * Adds the given texture to this scene.
  26744. * @param newTexture The texture to add
  26745. */
  26746. Scene.prototype.addTexture = function (newTexture) {
  26747. this.textures.push(newTexture);
  26748. };
  26749. /**
  26750. * Switch active camera
  26751. * @param newCamera defines the new active camera
  26752. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26753. */
  26754. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26755. if (attachControl === void 0) { attachControl = true; }
  26756. var canvas = this._engine.getRenderingCanvas();
  26757. if (!canvas) {
  26758. return;
  26759. }
  26760. if (this.activeCamera) {
  26761. this.activeCamera.detachControl(canvas);
  26762. }
  26763. this.activeCamera = newCamera;
  26764. if (attachControl) {
  26765. newCamera.attachControl(canvas);
  26766. }
  26767. };
  26768. /**
  26769. * sets the active camera of the scene using its ID
  26770. * @param id defines the camera's ID
  26771. * @return the new active camera or null if none found.
  26772. */
  26773. Scene.prototype.setActiveCameraByID = function (id) {
  26774. var camera = this.getCameraByID(id);
  26775. if (camera) {
  26776. this.activeCamera = camera;
  26777. return camera;
  26778. }
  26779. return null;
  26780. };
  26781. /**
  26782. * sets the active camera of the scene using its name
  26783. * @param name defines the camera's name
  26784. * @returns the new active camera or null if none found.
  26785. */
  26786. Scene.prototype.setActiveCameraByName = function (name) {
  26787. var camera = this.getCameraByName(name);
  26788. if (camera) {
  26789. this.activeCamera = camera;
  26790. return camera;
  26791. }
  26792. return null;
  26793. };
  26794. /**
  26795. * get an animation group using its name
  26796. * @param name defines the material's name
  26797. * @return the animation group or null if none found.
  26798. */
  26799. Scene.prototype.getAnimationGroupByName = function (name) {
  26800. for (var index = 0; index < this.animationGroups.length; index++) {
  26801. if (this.animationGroups[index].name === name) {
  26802. return this.animationGroups[index];
  26803. }
  26804. }
  26805. return null;
  26806. };
  26807. /**
  26808. * get a material using its id
  26809. * @param id defines the material's ID
  26810. * @return the material or null if none found.
  26811. */
  26812. Scene.prototype.getMaterialByID = function (id) {
  26813. for (var index = 0; index < this.materials.length; index++) {
  26814. if (this.materials[index].id === id) {
  26815. return this.materials[index];
  26816. }
  26817. }
  26818. return null;
  26819. };
  26820. /**
  26821. * Gets a material using its name
  26822. * @param name defines the material's name
  26823. * @return the material or null if none found.
  26824. */
  26825. Scene.prototype.getMaterialByName = function (name) {
  26826. for (var index = 0; index < this.materials.length; index++) {
  26827. if (this.materials[index].name === name) {
  26828. return this.materials[index];
  26829. }
  26830. }
  26831. return null;
  26832. };
  26833. /**
  26834. * Gets a lens flare system using its name
  26835. * @param name defines the name to look for
  26836. * @returns the lens flare system or null if not found
  26837. */
  26838. Scene.prototype.getLensFlareSystemByName = function (name) {
  26839. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26840. if (this.lensFlareSystems[index].name === name) {
  26841. return this.lensFlareSystems[index];
  26842. }
  26843. }
  26844. return null;
  26845. };
  26846. /**
  26847. * Gets a lens flare system using its id
  26848. * @param id defines the id to look for
  26849. * @returns the lens flare system or null if not found
  26850. */
  26851. Scene.prototype.getLensFlareSystemByID = function (id) {
  26852. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26853. if (this.lensFlareSystems[index].id === id) {
  26854. return this.lensFlareSystems[index];
  26855. }
  26856. }
  26857. return null;
  26858. };
  26859. /**
  26860. * Gets a camera using its id
  26861. * @param id defines the id to look for
  26862. * @returns the camera or null if not found
  26863. */
  26864. Scene.prototype.getCameraByID = function (id) {
  26865. for (var index = 0; index < this.cameras.length; index++) {
  26866. if (this.cameras[index].id === id) {
  26867. return this.cameras[index];
  26868. }
  26869. }
  26870. return null;
  26871. };
  26872. /**
  26873. * Gets a camera using its unique id
  26874. * @param uniqueId defines the unique id to look for
  26875. * @returns the camera or null if not found
  26876. */
  26877. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26878. for (var index = 0; index < this.cameras.length; index++) {
  26879. if (this.cameras[index].uniqueId === uniqueId) {
  26880. return this.cameras[index];
  26881. }
  26882. }
  26883. return null;
  26884. };
  26885. /**
  26886. * Gets a camera using its name
  26887. * @param name defines the camera's name
  26888. * @return the camera or null if none found.
  26889. */
  26890. Scene.prototype.getCameraByName = function (name) {
  26891. for (var index = 0; index < this.cameras.length; index++) {
  26892. if (this.cameras[index].name === name) {
  26893. return this.cameras[index];
  26894. }
  26895. }
  26896. return null;
  26897. };
  26898. /**
  26899. * Gets a bone using its id
  26900. * @param id defines the bone's id
  26901. * @return the bone or null if not found
  26902. */
  26903. Scene.prototype.getBoneByID = function (id) {
  26904. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26905. var skeleton = this.skeletons[skeletonIndex];
  26906. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26907. if (skeleton.bones[boneIndex].id === id) {
  26908. return skeleton.bones[boneIndex];
  26909. }
  26910. }
  26911. }
  26912. return null;
  26913. };
  26914. /**
  26915. * Gets a bone using its id
  26916. * @param name defines the bone's name
  26917. * @return the bone or null if not found
  26918. */
  26919. Scene.prototype.getBoneByName = function (name) {
  26920. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26921. var skeleton = this.skeletons[skeletonIndex];
  26922. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26923. if (skeleton.bones[boneIndex].name === name) {
  26924. return skeleton.bones[boneIndex];
  26925. }
  26926. }
  26927. }
  26928. return null;
  26929. };
  26930. /**
  26931. * Gets a light node using its name
  26932. * @param name defines the the light's name
  26933. * @return the light or null if none found.
  26934. */
  26935. Scene.prototype.getLightByName = function (name) {
  26936. for (var index = 0; index < this.lights.length; index++) {
  26937. if (this.lights[index].name === name) {
  26938. return this.lights[index];
  26939. }
  26940. }
  26941. return null;
  26942. };
  26943. /**
  26944. * Gets a light node using its id
  26945. * @param id defines the light's id
  26946. * @return the light or null if none found.
  26947. */
  26948. Scene.prototype.getLightByID = function (id) {
  26949. for (var index = 0; index < this.lights.length; index++) {
  26950. if (this.lights[index].id === id) {
  26951. return this.lights[index];
  26952. }
  26953. }
  26954. return null;
  26955. };
  26956. /**
  26957. * Gets a light node using its scene-generated unique ID
  26958. * @param uniqueId defines the light's unique id
  26959. * @return the light or null if none found.
  26960. */
  26961. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26962. for (var index = 0; index < this.lights.length; index++) {
  26963. if (this.lights[index].uniqueId === uniqueId) {
  26964. return this.lights[index];
  26965. }
  26966. }
  26967. return null;
  26968. };
  26969. /**
  26970. * Gets a particle system by id
  26971. * @param id defines the particle system id
  26972. * @return the corresponding system or null if none found
  26973. */
  26974. Scene.prototype.getParticleSystemByID = function (id) {
  26975. for (var index = 0; index < this.particleSystems.length; index++) {
  26976. if (this.particleSystems[index].id === id) {
  26977. return this.particleSystems[index];
  26978. }
  26979. }
  26980. return null;
  26981. };
  26982. /**
  26983. * Gets a geometry using its ID
  26984. * @param id defines the geometry's id
  26985. * @return the geometry or null if none found.
  26986. */
  26987. Scene.prototype.getGeometryByID = function (id) {
  26988. for (var index = 0; index < this._geometries.length; index++) {
  26989. if (this._geometries[index].id === id) {
  26990. return this._geometries[index];
  26991. }
  26992. }
  26993. return null;
  26994. };
  26995. /**
  26996. * Add a new geometry to this scene
  26997. * @param geometry defines the geometry to be added to the scene.
  26998. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26999. * @return a boolean defining if the geometry was added or not
  27000. */
  27001. Scene.prototype.pushGeometry = function (geometry, force) {
  27002. if (!force && this.getGeometryByID(geometry.id)) {
  27003. return false;
  27004. }
  27005. this._geometries.push(geometry);
  27006. //notify the collision coordinator
  27007. if (this.collisionCoordinator) {
  27008. this.collisionCoordinator.onGeometryAdded(geometry);
  27009. }
  27010. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27011. return true;
  27012. };
  27013. /**
  27014. * Removes an existing geometry
  27015. * @param geometry defines the geometry to be removed from the scene
  27016. * @return a boolean defining if the geometry was removed or not
  27017. */
  27018. Scene.prototype.removeGeometry = function (geometry) {
  27019. var index = this._geometries.indexOf(geometry);
  27020. if (index > -1) {
  27021. this._geometries.splice(index, 1);
  27022. //notify the collision coordinator
  27023. if (this.collisionCoordinator) {
  27024. this.collisionCoordinator.onGeometryDeleted(geometry);
  27025. }
  27026. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27027. return true;
  27028. }
  27029. return false;
  27030. };
  27031. /**
  27032. * Gets the list of geometries attached to the scene
  27033. * @returns an array of Geometry
  27034. */
  27035. Scene.prototype.getGeometries = function () {
  27036. return this._geometries;
  27037. };
  27038. /**
  27039. * Gets the first added mesh found of a given ID
  27040. * @param id defines the id to search for
  27041. * @return the mesh found or null if not found at all
  27042. */
  27043. Scene.prototype.getMeshByID = function (id) {
  27044. for (var index = 0; index < this.meshes.length; index++) {
  27045. if (this.meshes[index].id === id) {
  27046. return this.meshes[index];
  27047. }
  27048. }
  27049. return null;
  27050. };
  27051. /**
  27052. * Gets a list of meshes using their id
  27053. * @param id defines the id to search for
  27054. * @returns a list of meshes
  27055. */
  27056. Scene.prototype.getMeshesByID = function (id) {
  27057. return this.meshes.filter(function (m) {
  27058. return m.id === id;
  27059. });
  27060. };
  27061. /**
  27062. * Gets the first added transform node found of a given ID
  27063. * @param id defines the id to search for
  27064. * @return the found transform node or null if not found at all.
  27065. */
  27066. Scene.prototype.getTransformNodeByID = function (id) {
  27067. for (var index = 0; index < this.transformNodes.length; index++) {
  27068. if (this.transformNodes[index].id === id) {
  27069. return this.transformNodes[index];
  27070. }
  27071. }
  27072. return null;
  27073. };
  27074. /**
  27075. * Gets a list of transform nodes using their id
  27076. * @param id defines the id to search for
  27077. * @returns a list of transform nodes
  27078. */
  27079. Scene.prototype.getTransformNodesByID = function (id) {
  27080. return this.transformNodes.filter(function (m) {
  27081. return m.id === id;
  27082. });
  27083. };
  27084. /**
  27085. * Gets a mesh with its auto-generated unique id
  27086. * @param uniqueId defines the unique id to search for
  27087. * @return the found mesh or null if not found at all.
  27088. */
  27089. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27090. for (var index = 0; index < this.meshes.length; index++) {
  27091. if (this.meshes[index].uniqueId === uniqueId) {
  27092. return this.meshes[index];
  27093. }
  27094. }
  27095. return null;
  27096. };
  27097. /**
  27098. * Gets a the last added mesh using a given id
  27099. * @param id defines the id to search for
  27100. * @return the found mesh or null if not found at all.
  27101. */
  27102. Scene.prototype.getLastMeshByID = function (id) {
  27103. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27104. if (this.meshes[index].id === id) {
  27105. return this.meshes[index];
  27106. }
  27107. }
  27108. return null;
  27109. };
  27110. /**
  27111. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27112. * @param id defines the id to search for
  27113. * @return the found node or null if not found at all
  27114. */
  27115. Scene.prototype.getLastEntryByID = function (id) {
  27116. var index;
  27117. for (index = this.meshes.length - 1; index >= 0; index--) {
  27118. if (this.meshes[index].id === id) {
  27119. return this.meshes[index];
  27120. }
  27121. }
  27122. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27123. if (this.transformNodes[index].id === id) {
  27124. return this.transformNodes[index];
  27125. }
  27126. }
  27127. for (index = this.cameras.length - 1; index >= 0; index--) {
  27128. if (this.cameras[index].id === id) {
  27129. return this.cameras[index];
  27130. }
  27131. }
  27132. for (index = this.lights.length - 1; index >= 0; index--) {
  27133. if (this.lights[index].id === id) {
  27134. return this.lights[index];
  27135. }
  27136. }
  27137. return null;
  27138. };
  27139. /**
  27140. * Gets a node (Mesh, Camera, Light) using a given id
  27141. * @param id defines the id to search for
  27142. * @return the found node or null if not found at all
  27143. */
  27144. Scene.prototype.getNodeByID = function (id) {
  27145. var mesh = this.getMeshByID(id);
  27146. if (mesh) {
  27147. return mesh;
  27148. }
  27149. var light = this.getLightByID(id);
  27150. if (light) {
  27151. return light;
  27152. }
  27153. var camera = this.getCameraByID(id);
  27154. if (camera) {
  27155. return camera;
  27156. }
  27157. var bone = this.getBoneByID(id);
  27158. return bone;
  27159. };
  27160. /**
  27161. * Gets a node (Mesh, Camera, Light) using a given name
  27162. * @param name defines the name to search for
  27163. * @return the found node or null if not found at all.
  27164. */
  27165. Scene.prototype.getNodeByName = function (name) {
  27166. var mesh = this.getMeshByName(name);
  27167. if (mesh) {
  27168. return mesh;
  27169. }
  27170. var light = this.getLightByName(name);
  27171. if (light) {
  27172. return light;
  27173. }
  27174. var camera = this.getCameraByName(name);
  27175. if (camera) {
  27176. return camera;
  27177. }
  27178. var bone = this.getBoneByName(name);
  27179. return bone;
  27180. };
  27181. /**
  27182. * Gets a mesh using a given name
  27183. * @param name defines the name to search for
  27184. * @return the found mesh or null if not found at all.
  27185. */
  27186. Scene.prototype.getMeshByName = function (name) {
  27187. for (var index = 0; index < this.meshes.length; index++) {
  27188. if (this.meshes[index].name === name) {
  27189. return this.meshes[index];
  27190. }
  27191. }
  27192. return null;
  27193. };
  27194. /**
  27195. * Gets a transform node using a given name
  27196. * @param name defines the name to search for
  27197. * @return the found transform node or null if not found at all.
  27198. */
  27199. Scene.prototype.getTransformNodeByName = function (name) {
  27200. for (var index = 0; index < this.transformNodes.length; index++) {
  27201. if (this.transformNodes[index].name === name) {
  27202. return this.transformNodes[index];
  27203. }
  27204. }
  27205. return null;
  27206. };
  27207. /**
  27208. * Gets a sound using a given name
  27209. * @param name defines the name to search for
  27210. * @return the found sound or null if not found at all.
  27211. */
  27212. Scene.prototype.getSoundByName = function (name) {
  27213. var index;
  27214. if (BABYLON.AudioEngine) {
  27215. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27216. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27217. return this.mainSoundTrack.soundCollection[index];
  27218. }
  27219. }
  27220. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27221. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27222. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27223. return this.soundTracks[sdIndex].soundCollection[index];
  27224. }
  27225. }
  27226. }
  27227. }
  27228. return null;
  27229. };
  27230. /**
  27231. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27232. * @param id defines the id to search for
  27233. * @return the found skeleton or null if not found at all.
  27234. */
  27235. Scene.prototype.getLastSkeletonByID = function (id) {
  27236. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27237. if (this.skeletons[index].id === id) {
  27238. return this.skeletons[index];
  27239. }
  27240. }
  27241. return null;
  27242. };
  27243. /**
  27244. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27245. * @param id defines the id to search for
  27246. * @return the found skeleton or null if not found at all.
  27247. */
  27248. Scene.prototype.getSkeletonById = function (id) {
  27249. for (var index = 0; index < this.skeletons.length; index++) {
  27250. if (this.skeletons[index].id === id) {
  27251. return this.skeletons[index];
  27252. }
  27253. }
  27254. return null;
  27255. };
  27256. /**
  27257. * Gets a skeleton using a given name
  27258. * @param name defines the name to search for
  27259. * @return the found skeleton or null if not found at all.
  27260. */
  27261. Scene.prototype.getSkeletonByName = function (name) {
  27262. for (var index = 0; index < this.skeletons.length; index++) {
  27263. if (this.skeletons[index].name === name) {
  27264. return this.skeletons[index];
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27271. * @param id defines the id to search for
  27272. * @return the found morph target manager or null if not found at all.
  27273. */
  27274. Scene.prototype.getMorphTargetManagerById = function (id) {
  27275. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27276. if (this.morphTargetManagers[index].uniqueId === id) {
  27277. return this.morphTargetManagers[index];
  27278. }
  27279. }
  27280. return null;
  27281. };
  27282. /**
  27283. * Gets a boolean indicating if the given mesh is active
  27284. * @param mesh defines the mesh to look for
  27285. * @returns true if the mesh is in the active list
  27286. */
  27287. Scene.prototype.isActiveMesh = function (mesh) {
  27288. return (this._activeMeshes.indexOf(mesh) !== -1);
  27289. };
  27290. /**
  27291. * Return a the first highlight layer of the scene with a given name.
  27292. * @param name The name of the highlight layer to look for.
  27293. * @return The highlight layer if found otherwise null.
  27294. */
  27295. Scene.prototype.getHighlightLayerByName = function (name) {
  27296. for (var index = 0; index < this.effectLayers.length; index++) {
  27297. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27298. return this.effectLayers[index];
  27299. }
  27300. }
  27301. return null;
  27302. };
  27303. /**
  27304. * Return a the first highlight layer of the scene with a given name.
  27305. * @param name The name of the highlight layer to look for.
  27306. * @return The highlight layer if found otherwise null.
  27307. */
  27308. Scene.prototype.getGlowLayerByName = function (name) {
  27309. for (var index = 0; index < this.effectLayers.length; index++) {
  27310. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27311. return this.effectLayers[index];
  27312. }
  27313. }
  27314. return null;
  27315. };
  27316. Object.defineProperty(Scene.prototype, "uid", {
  27317. /**
  27318. * Return a unique id as a string which can serve as an identifier for the scene
  27319. */
  27320. get: function () {
  27321. if (!this._uid) {
  27322. this._uid = BABYLON.Tools.RandomId();
  27323. }
  27324. return this._uid;
  27325. },
  27326. enumerable: true,
  27327. configurable: true
  27328. });
  27329. /**
  27330. * Add an externaly attached data from its key.
  27331. * This method call will fail and return false, if such key already exists.
  27332. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27333. * @param key the unique key that identifies the data
  27334. * @param data the data object to associate to the key for this Engine instance
  27335. * @return true if no such key were already present and the data was added successfully, false otherwise
  27336. */
  27337. Scene.prototype.addExternalData = function (key, data) {
  27338. if (!this._externalData) {
  27339. this._externalData = new BABYLON.StringDictionary();
  27340. }
  27341. return this._externalData.add(key, data);
  27342. };
  27343. /**
  27344. * Get an externaly attached data from its key
  27345. * @param key the unique key that identifies the data
  27346. * @return the associated data, if present (can be null), or undefined if not present
  27347. */
  27348. Scene.prototype.getExternalData = function (key) {
  27349. if (!this._externalData) {
  27350. return null;
  27351. }
  27352. return this._externalData.get(key);
  27353. };
  27354. /**
  27355. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27356. * @param key the unique key that identifies the data
  27357. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27358. * @return the associated data, can be null if the factory returned null.
  27359. */
  27360. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27361. if (!this._externalData) {
  27362. this._externalData = new BABYLON.StringDictionary();
  27363. }
  27364. return this._externalData.getOrAddWithFactory(key, factory);
  27365. };
  27366. /**
  27367. * Remove an externaly attached data from the Engine instance
  27368. * @param key the unique key that identifies the data
  27369. * @return true if the data was successfully removed, false if it doesn't exist
  27370. */
  27371. Scene.prototype.removeExternalData = function (key) {
  27372. return this._externalData.remove(key);
  27373. };
  27374. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27375. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27376. if (mesh.showSubMeshesBoundingBox) {
  27377. var boundingInfo = subMesh.getBoundingInfo();
  27378. if (boundingInfo !== null && boundingInfo !== undefined) {
  27379. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27380. }
  27381. }
  27382. var material = subMesh.getMaterial();
  27383. if (material !== null && material !== undefined) {
  27384. // Render targets
  27385. if (material.getRenderTargetTextures !== undefined) {
  27386. if (this._processedMaterials.indexOf(material) === -1) {
  27387. this._processedMaterials.push(material);
  27388. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27389. }
  27390. }
  27391. // Dispatch
  27392. this._activeIndices.addCount(subMesh.indexCount, false);
  27393. this._renderingManager.dispatch(subMesh, mesh, material);
  27394. }
  27395. }
  27396. };
  27397. /**
  27398. * Clear the processed materials smart array preventing retention point in material dispose.
  27399. */
  27400. Scene.prototype.freeProcessedMaterials = function () {
  27401. this._processedMaterials.dispose();
  27402. };
  27403. /**
  27404. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27405. */
  27406. Scene.prototype.freeActiveMeshes = function () {
  27407. this._activeMeshes.dispose();
  27408. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27409. this.activeCamera._activeMeshes.dispose();
  27410. }
  27411. if (this.activeCameras) {
  27412. for (var i = 0; i < this.activeCameras.length; i++) {
  27413. var activeCamera = this.activeCameras[i];
  27414. if (activeCamera && activeCamera._activeMeshes) {
  27415. activeCamera._activeMeshes.dispose();
  27416. }
  27417. }
  27418. }
  27419. };
  27420. /**
  27421. * Clear the info related to rendering groups preventing retention points during dispose.
  27422. */
  27423. Scene.prototype.freeRenderingGroups = function () {
  27424. if (this._renderingManager) {
  27425. this._renderingManager.freeRenderingGroups();
  27426. }
  27427. if (this.textures) {
  27428. for (var i = 0; i < this.textures.length; i++) {
  27429. var texture = this.textures[i];
  27430. if (texture && texture.renderList) {
  27431. texture.freeRenderingGroups();
  27432. }
  27433. }
  27434. }
  27435. };
  27436. /** @hidden */
  27437. Scene.prototype._isInIntermediateRendering = function () {
  27438. return this._intermediateRendering;
  27439. };
  27440. /**
  27441. * Defines the current active mesh candidate provider
  27442. * @param provider defines the provider to use
  27443. */
  27444. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27445. this._activeMeshCandidateProvider = provider;
  27446. };
  27447. /**
  27448. * Gets the current active mesh candidate provider
  27449. * @returns the current active mesh candidate provider
  27450. */
  27451. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27452. return this._activeMeshCandidateProvider;
  27453. };
  27454. /**
  27455. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27456. * @returns the current scene
  27457. */
  27458. Scene.prototype.freezeActiveMeshes = function () {
  27459. if (!this.activeCamera) {
  27460. return this;
  27461. }
  27462. if (!this._frustumPlanes) {
  27463. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27464. }
  27465. this._evaluateActiveMeshes();
  27466. this._activeMeshesFrozen = true;
  27467. return this;
  27468. };
  27469. /**
  27470. * Use this function to restart evaluating active meshes on every frame
  27471. * @returns the current scene
  27472. */
  27473. Scene.prototype.unfreezeActiveMeshes = function () {
  27474. this._activeMeshesFrozen = false;
  27475. return this;
  27476. };
  27477. Scene.prototype._evaluateActiveMeshes = function () {
  27478. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27479. return;
  27480. }
  27481. if (!this.activeCamera) {
  27482. return;
  27483. }
  27484. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27485. this.activeCamera._activeMeshes.reset();
  27486. this._activeMeshes.reset();
  27487. this._renderingManager.reset();
  27488. this._processedMaterials.reset();
  27489. this._activeParticleSystems.reset();
  27490. this._activeSkeletons.reset();
  27491. this._softwareSkinnedMeshes.reset();
  27492. if (this._boundingBoxRenderer) {
  27493. this._boundingBoxRenderer.reset();
  27494. }
  27495. // Meshes
  27496. var meshes;
  27497. var len;
  27498. var checkIsEnabled = true;
  27499. // Determine mesh candidates
  27500. if (this._activeMeshCandidateProvider !== undefined) {
  27501. // Use _activeMeshCandidateProvider
  27502. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27503. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27504. if (meshes !== undefined) {
  27505. len = meshes.length;
  27506. }
  27507. else {
  27508. len = 0;
  27509. }
  27510. }
  27511. else if (this._selectionOctree !== undefined) {
  27512. // Octree
  27513. var selection = this._selectionOctree.select(this._frustumPlanes);
  27514. meshes = selection.data;
  27515. len = selection.length;
  27516. }
  27517. else {
  27518. // Full scene traversal
  27519. len = this.meshes.length;
  27520. meshes = this.meshes;
  27521. }
  27522. // Check each mesh
  27523. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27524. mesh = meshes[meshIndex];
  27525. if (mesh.isBlocked) {
  27526. continue;
  27527. }
  27528. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27529. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27530. continue;
  27531. }
  27532. mesh.computeWorldMatrix();
  27533. // Intersections
  27534. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27535. this._meshesForIntersections.pushNoDuplicate(mesh);
  27536. }
  27537. // Switch to current LOD
  27538. meshLOD = mesh.getLOD(this.activeCamera);
  27539. if (meshLOD === undefined || meshLOD === null) {
  27540. continue;
  27541. }
  27542. mesh._preActivate();
  27543. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27544. this._activeMeshes.push(mesh);
  27545. this.activeCamera._activeMeshes.push(mesh);
  27546. mesh._activate(this._renderId);
  27547. if (meshLOD !== mesh) {
  27548. meshLOD._activate(this._renderId);
  27549. }
  27550. this._activeMesh(mesh, meshLOD);
  27551. }
  27552. }
  27553. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27554. // Particle systems
  27555. if (this.particlesEnabled) {
  27556. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27557. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27558. var particleSystem = this.particleSystems[particleIndex];
  27559. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27560. continue;
  27561. }
  27562. var emitter = particleSystem.emitter;
  27563. if (!emitter.position || emitter.isEnabled()) {
  27564. this._activeParticleSystems.push(particleSystem);
  27565. particleSystem.animate();
  27566. this._renderingManager.dispatchParticles(particleSystem);
  27567. }
  27568. }
  27569. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27570. }
  27571. };
  27572. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27573. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27574. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27575. mesh.skeleton.prepare();
  27576. }
  27577. if (!mesh.computeBonesUsingShaders) {
  27578. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27579. }
  27580. }
  27581. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27582. var boundingInfo = sourceMesh.getBoundingInfo();
  27583. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27584. }
  27585. if (mesh !== undefined && mesh !== null
  27586. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27587. // Submeshes Octrees
  27588. var len;
  27589. var subMeshes;
  27590. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27591. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27592. len = intersections.length;
  27593. subMeshes = intersections.data;
  27594. }
  27595. else {
  27596. subMeshes = mesh.subMeshes;
  27597. len = subMeshes.length;
  27598. }
  27599. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27600. subMesh = subMeshes[subIndex];
  27601. this._evaluateSubMesh(subMesh, mesh);
  27602. }
  27603. }
  27604. };
  27605. /**
  27606. * Update the transform matrix to update from the current active camera
  27607. * @param force defines a boolean used to force the update even if cache is up to date
  27608. */
  27609. Scene.prototype.updateTransformMatrix = function (force) {
  27610. if (!this.activeCamera) {
  27611. return;
  27612. }
  27613. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27614. };
  27615. /**
  27616. * 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)
  27617. * @param alternateCamera defines the camera to use
  27618. */
  27619. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27620. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27621. };
  27622. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27623. if (camera && camera._skipRendering) {
  27624. return;
  27625. }
  27626. var engine = this._engine;
  27627. this.activeCamera = camera;
  27628. if (!this.activeCamera)
  27629. throw new Error("Active camera not set");
  27630. // Viewport
  27631. engine.setViewport(this.activeCamera.viewport);
  27632. // Camera
  27633. this.resetCachedMaterial();
  27634. this._renderId++;
  27635. this.updateTransformMatrix();
  27636. if (camera._alternateCamera) {
  27637. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27638. this._alternateRendering = true;
  27639. }
  27640. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27641. // Meshes
  27642. this._evaluateActiveMeshes();
  27643. // Software skinning
  27644. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27645. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27646. mesh.applySkeleton(mesh.skeleton);
  27647. }
  27648. // Render targets
  27649. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27650. var needsRestoreFrameBuffer = false;
  27651. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27652. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27653. }
  27654. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27655. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27656. }
  27657. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27658. this._intermediateRendering = true;
  27659. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27660. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27661. var renderTarget = this._renderTargets.data[renderIndex];
  27662. if (renderTarget._shouldRender()) {
  27663. this._renderId++;
  27664. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27665. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27666. }
  27667. }
  27668. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27669. this._intermediateRendering = false;
  27670. this._renderId++;
  27671. needsRestoreFrameBuffer = true; // Restore back buffer
  27672. }
  27673. // Render EffectLayer Texture
  27674. var stencilState = this._engine.getStencilBuffer();
  27675. var renderEffects = false;
  27676. var needStencil = false;
  27677. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27678. this._intermediateRendering = true;
  27679. for (var i = 0; i < this.effectLayers.length; i++) {
  27680. var effectLayer = this.effectLayers[i];
  27681. if (effectLayer.shouldRender() &&
  27682. (!effectLayer.camera ||
  27683. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27684. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27685. renderEffects = true;
  27686. needStencil = needStencil || effectLayer.needStencil();
  27687. var renderTarget = effectLayer._mainTexture;
  27688. if (renderTarget._shouldRender()) {
  27689. this._renderId++;
  27690. renderTarget.render(false, false);
  27691. needsRestoreFrameBuffer = true;
  27692. }
  27693. }
  27694. }
  27695. this._intermediateRendering = false;
  27696. this._renderId++;
  27697. }
  27698. if (needsRestoreFrameBuffer) {
  27699. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27700. }
  27701. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27702. // Prepare Frame
  27703. if (this.postProcessManager) {
  27704. this.postProcessManager._prepareFrame();
  27705. }
  27706. // Backgrounds
  27707. var layerIndex;
  27708. var layer;
  27709. if (this.layers.length) {
  27710. engine.setDepthBuffer(false);
  27711. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27712. layer = this.layers[layerIndex];
  27713. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27714. layer.render();
  27715. }
  27716. }
  27717. engine.setDepthBuffer(true);
  27718. }
  27719. // Activate effect Layer stencil
  27720. if (needStencil) {
  27721. this._engine.setStencilBuffer(true);
  27722. }
  27723. // Render
  27724. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27725. this._renderingManager.render(null, null, true, true);
  27726. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27727. // Restore effect Layer stencil
  27728. if (needStencil) {
  27729. this._engine.setStencilBuffer(stencilState);
  27730. }
  27731. // Bounding boxes
  27732. if (this._boundingBoxRenderer) {
  27733. this._boundingBoxRenderer.render();
  27734. }
  27735. // Lens flares
  27736. if (this.lensFlaresEnabled) {
  27737. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27738. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27739. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27740. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27741. lensFlareSystem.render();
  27742. }
  27743. }
  27744. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27745. }
  27746. // Effect Layer
  27747. if (renderEffects) {
  27748. engine.setDepthBuffer(false);
  27749. for (var i = 0; i < this.effectLayers.length; i++) {
  27750. if (this.effectLayers[i].shouldRender()) {
  27751. this.effectLayers[i].render();
  27752. }
  27753. }
  27754. engine.setDepthBuffer(true);
  27755. }
  27756. // Foregrounds
  27757. if (this.layers.length) {
  27758. engine.setDepthBuffer(false);
  27759. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27760. layer = this.layers[layerIndex];
  27761. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27762. layer.render();
  27763. }
  27764. }
  27765. engine.setDepthBuffer(true);
  27766. }
  27767. // Finalize frame
  27768. if (this.postProcessManager) {
  27769. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27770. }
  27771. // Reset some special arrays
  27772. this._renderTargets.reset();
  27773. this._alternateRendering = false;
  27774. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27775. };
  27776. Scene.prototype._processSubCameras = function (camera) {
  27777. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27778. this._renderForCamera(camera);
  27779. return;
  27780. }
  27781. // rig cameras
  27782. for (var index = 0; index < camera._rigCameras.length; index++) {
  27783. this._renderForCamera(camera._rigCameras[index], camera);
  27784. }
  27785. this.activeCamera = camera;
  27786. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27787. };
  27788. Scene.prototype._checkIntersections = function () {
  27789. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27790. var sourceMesh = this._meshesForIntersections.data[index];
  27791. if (!sourceMesh.actionManager) {
  27792. continue;
  27793. }
  27794. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27795. var action = sourceMesh.actionManager.actions[actionIndex];
  27796. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27797. var parameters = action.getTriggerParameter();
  27798. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27799. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27800. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27801. if (areIntersecting && currentIntersectionInProgress === -1) {
  27802. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27803. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27804. sourceMesh._intersectionsInProgress.push(otherMesh);
  27805. }
  27806. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27807. sourceMesh._intersectionsInProgress.push(otherMesh);
  27808. }
  27809. }
  27810. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27811. //They intersected, and now they don't.
  27812. //is this trigger an exit trigger? execute an event.
  27813. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27814. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27815. }
  27816. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27817. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27818. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27819. return otherMesh === parameterMesh;
  27820. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27821. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27822. }
  27823. }
  27824. }
  27825. }
  27826. }
  27827. };
  27828. /**
  27829. * Render the scene
  27830. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27831. */
  27832. Scene.prototype.render = function (updateCameras) {
  27833. if (updateCameras === void 0) { updateCameras = true; }
  27834. if (this.isDisposed) {
  27835. return;
  27836. }
  27837. this._activeParticles.fetchNewFrame();
  27838. this._totalVertices.fetchNewFrame();
  27839. this._activeIndices.fetchNewFrame();
  27840. this._activeBones.fetchNewFrame();
  27841. this._meshesForIntersections.reset();
  27842. this.resetCachedMaterial();
  27843. this.onBeforeAnimationsObservable.notifyObservers(this);
  27844. // Actions
  27845. if (this.actionManager) {
  27846. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27847. }
  27848. //Simplification Queue
  27849. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27850. this.simplificationQueue.executeNext();
  27851. }
  27852. if (this._engine.isDeterministicLockStep()) {
  27853. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27854. var defaultFPS = (60.0 / 1000.0);
  27855. var defaultFrameTime = 1000 / 60; // frame time in MS
  27856. if (this._physicsEngine) {
  27857. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27858. }
  27859. var stepsTaken = 0;
  27860. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27861. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27862. internalSteps = Math.min(internalSteps, maxSubSteps);
  27863. do {
  27864. this.onBeforeStepObservable.notifyObservers(this);
  27865. // Animations
  27866. this._animationRatio = defaultFrameTime * defaultFPS;
  27867. this._animate();
  27868. this.onAfterAnimationsObservable.notifyObservers(this);
  27869. // Physics
  27870. if (this._physicsEngine) {
  27871. this.onBeforePhysicsObservable.notifyObservers(this);
  27872. this._physicsEngine._step(defaultFrameTime / 1000);
  27873. this.onAfterPhysicsObservable.notifyObservers(this);
  27874. }
  27875. this.onAfterStepObservable.notifyObservers(this);
  27876. this._currentStepId++;
  27877. stepsTaken++;
  27878. deltaTime -= defaultFrameTime;
  27879. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27880. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27881. }
  27882. else {
  27883. // Animations
  27884. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27885. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27886. this._animate();
  27887. this.onAfterAnimationsObservable.notifyObservers(this);
  27888. // Physics
  27889. if (this._physicsEngine) {
  27890. this.onBeforePhysicsObservable.notifyObservers(this);
  27891. this._physicsEngine._step(deltaTime / 1000.0);
  27892. this.onAfterPhysicsObservable.notifyObservers(this);
  27893. }
  27894. }
  27895. // update gamepad manager
  27896. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27897. this._gamepadManager._checkGamepadsStatus();
  27898. }
  27899. // Update Cameras
  27900. if (updateCameras) {
  27901. if (this.activeCameras.length > 0) {
  27902. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27903. var camera = this.activeCameras[cameraIndex];
  27904. camera.update();
  27905. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27906. // rig cameras
  27907. for (var index = 0; index < camera._rigCameras.length; index++) {
  27908. camera._rigCameras[index].update();
  27909. }
  27910. }
  27911. }
  27912. }
  27913. else if (this.activeCamera) {
  27914. this.activeCamera.update();
  27915. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27916. // rig cameras
  27917. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27918. this.activeCamera._rigCameras[index].update();
  27919. }
  27920. }
  27921. }
  27922. }
  27923. // Before render
  27924. this.onBeforeRenderObservable.notifyObservers(this);
  27925. // Customs render targets
  27926. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27927. var engine = this.getEngine();
  27928. var currentActiveCamera = this.activeCamera;
  27929. if (this.renderTargetsEnabled) {
  27930. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27931. this._intermediateRendering = true;
  27932. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27933. var renderTarget = this.customRenderTargets[customIndex];
  27934. if (renderTarget._shouldRender()) {
  27935. this._renderId++;
  27936. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27937. if (!this.activeCamera)
  27938. throw new Error("Active camera not set");
  27939. // Viewport
  27940. engine.setViewport(this.activeCamera.viewport);
  27941. // Camera
  27942. this.updateTransformMatrix();
  27943. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27944. }
  27945. }
  27946. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27947. this._intermediateRendering = false;
  27948. this._renderId++;
  27949. }
  27950. // Restore back buffer
  27951. if (this.customRenderTargets.length > 0) {
  27952. engine.restoreDefaultFramebuffer();
  27953. }
  27954. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27955. this.activeCamera = currentActiveCamera;
  27956. // Procedural textures
  27957. if (this.proceduralTexturesEnabled) {
  27958. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27959. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27960. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27961. if (proceduralTexture._shouldRender()) {
  27962. proceduralTexture.render();
  27963. }
  27964. }
  27965. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27966. }
  27967. // Clear
  27968. if (this.autoClearDepthAndStencil || this.autoClear) {
  27969. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27970. }
  27971. // Shadows
  27972. if (this.shadowsEnabled) {
  27973. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27974. var light = this.lights[lightIndex];
  27975. var shadowGenerator = light.getShadowGenerator();
  27976. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27977. var shadowMap = (shadowGenerator.getShadowMap());
  27978. if (this.textures.indexOf(shadowMap) !== -1) {
  27979. this._renderTargets.push(shadowMap);
  27980. }
  27981. }
  27982. }
  27983. }
  27984. // Depth renderer
  27985. for (var key in this._depthRenderer) {
  27986. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27987. }
  27988. // Geometry renderer
  27989. if (this._geometryBufferRenderer) {
  27990. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27991. }
  27992. // RenderPipeline
  27993. if (this._postProcessRenderPipelineManager) {
  27994. this._postProcessRenderPipelineManager.update();
  27995. }
  27996. // Multi-cameras?
  27997. if (this.activeCameras.length > 0) {
  27998. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27999. if (cameraIndex > 0) {
  28000. this._engine.clear(null, false, true, true);
  28001. }
  28002. this._processSubCameras(this.activeCameras[cameraIndex]);
  28003. }
  28004. }
  28005. else {
  28006. if (!this.activeCamera) {
  28007. throw new Error("No camera defined");
  28008. }
  28009. this._processSubCameras(this.activeCamera);
  28010. }
  28011. // Intersection checks
  28012. this._checkIntersections();
  28013. // Update the audio listener attached to the camera
  28014. if (BABYLON.AudioEngine) {
  28015. this._updateAudioParameters();
  28016. }
  28017. // After render
  28018. if (this.afterRender) {
  28019. this.afterRender();
  28020. }
  28021. this.onAfterRenderObservable.notifyObservers(this);
  28022. // Cleaning
  28023. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28024. var data = this._toBeDisposed.data[index];
  28025. if (data) {
  28026. data.dispose();
  28027. }
  28028. this._toBeDisposed[index] = null;
  28029. }
  28030. this._toBeDisposed.reset();
  28031. if (this.dumpNextRenderTargets) {
  28032. this.dumpNextRenderTargets = false;
  28033. }
  28034. this._activeBones.addCount(0, true);
  28035. this._activeIndices.addCount(0, true);
  28036. this._activeParticles.addCount(0, true);
  28037. };
  28038. Scene.prototype._updateAudioParameters = function () {
  28039. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28040. return;
  28041. }
  28042. var listeningCamera;
  28043. var audioEngine = BABYLON.Engine.audioEngine;
  28044. if (this.activeCameras.length > 0) {
  28045. listeningCamera = this.activeCameras[0];
  28046. }
  28047. else {
  28048. listeningCamera = this.activeCamera;
  28049. }
  28050. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28051. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28052. // for VR cameras
  28053. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28054. listeningCamera = listeningCamera.rigCameras[0];
  28055. }
  28056. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28057. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28058. cameraDirection.normalize();
  28059. // To avoid some errors on GearVR
  28060. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28061. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28062. }
  28063. var i;
  28064. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28065. var sound = this.mainSoundTrack.soundCollection[i];
  28066. if (sound.useCustomAttenuation) {
  28067. sound.updateDistanceFromListener();
  28068. }
  28069. }
  28070. for (i = 0; i < this.soundTracks.length; i++) {
  28071. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28072. sound = this.soundTracks[i].soundCollection[j];
  28073. if (sound.useCustomAttenuation) {
  28074. sound.updateDistanceFromListener();
  28075. }
  28076. }
  28077. }
  28078. }
  28079. };
  28080. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28081. // Audio
  28082. /**
  28083. * Gets or sets if audio support is enabled
  28084. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28085. */
  28086. get: function () {
  28087. return this._audioEnabled;
  28088. },
  28089. set: function (value) {
  28090. this._audioEnabled = value;
  28091. if (BABYLON.AudioEngine) {
  28092. if (this._audioEnabled) {
  28093. this._enableAudio();
  28094. }
  28095. else {
  28096. this._disableAudio();
  28097. }
  28098. }
  28099. },
  28100. enumerable: true,
  28101. configurable: true
  28102. });
  28103. Scene.prototype._disableAudio = function () {
  28104. var i;
  28105. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28106. this.mainSoundTrack.soundCollection[i].pause();
  28107. }
  28108. for (i = 0; i < this.soundTracks.length; i++) {
  28109. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28110. this.soundTracks[i].soundCollection[j].pause();
  28111. }
  28112. }
  28113. };
  28114. Scene.prototype._enableAudio = function () {
  28115. var i;
  28116. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28117. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28118. this.mainSoundTrack.soundCollection[i].play();
  28119. }
  28120. }
  28121. for (i = 0; i < this.soundTracks.length; i++) {
  28122. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28123. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28124. this.soundTracks[i].soundCollection[j].play();
  28125. }
  28126. }
  28127. }
  28128. };
  28129. Object.defineProperty(Scene.prototype, "headphone", {
  28130. /**
  28131. * Gets or sets if audio will be output to headphones
  28132. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28133. */
  28134. get: function () {
  28135. return this._headphone;
  28136. },
  28137. set: function (value) {
  28138. this._headphone = value;
  28139. if (BABYLON.AudioEngine) {
  28140. if (this._headphone) {
  28141. this._switchAudioModeForHeadphones();
  28142. }
  28143. else {
  28144. this._switchAudioModeForNormalSpeakers();
  28145. }
  28146. }
  28147. },
  28148. enumerable: true,
  28149. configurable: true
  28150. });
  28151. Scene.prototype._switchAudioModeForHeadphones = function () {
  28152. this.mainSoundTrack.switchPanningModelToHRTF();
  28153. for (var i = 0; i < this.soundTracks.length; i++) {
  28154. this.soundTracks[i].switchPanningModelToHRTF();
  28155. }
  28156. };
  28157. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28158. this.mainSoundTrack.switchPanningModelToEqualPower();
  28159. for (var i = 0; i < this.soundTracks.length; i++) {
  28160. this.soundTracks[i].switchPanningModelToEqualPower();
  28161. }
  28162. };
  28163. /**
  28164. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28165. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28166. * @returns the created depth renderer
  28167. */
  28168. Scene.prototype.enableDepthRenderer = function (camera) {
  28169. camera = camera || this.activeCamera;
  28170. if (!camera) {
  28171. throw "No camera available to enable depth renderer";
  28172. }
  28173. if (!this._depthRenderer[camera.id]) {
  28174. var textureType = 0;
  28175. if (this._engine.getCaps().textureHalfFloatRender) {
  28176. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28177. }
  28178. else if (this._engine.getCaps().textureFloatRender) {
  28179. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28180. }
  28181. else {
  28182. throw "Depth renderer does not support int texture type";
  28183. }
  28184. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28185. }
  28186. return this._depthRenderer[camera.id];
  28187. };
  28188. /**
  28189. * Disables a depth renderer for a given camera
  28190. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28191. */
  28192. Scene.prototype.disableDepthRenderer = function (camera) {
  28193. camera = camera || this.activeCamera;
  28194. if (!camera || !this._depthRenderer[camera.id]) {
  28195. return;
  28196. }
  28197. this._depthRenderer[camera.id].dispose();
  28198. delete this._depthRenderer[camera.id];
  28199. };
  28200. /**
  28201. * Enables a GeometryBufferRender and associates it with the scene
  28202. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28203. * @returns the GeometryBufferRenderer
  28204. */
  28205. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28206. if (ratio === void 0) { ratio = 1; }
  28207. if (this._geometryBufferRenderer) {
  28208. return this._geometryBufferRenderer;
  28209. }
  28210. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28211. if (!this._geometryBufferRenderer.isSupported) {
  28212. this._geometryBufferRenderer = null;
  28213. }
  28214. return this._geometryBufferRenderer;
  28215. };
  28216. /**
  28217. * Disables the GeometryBufferRender associated with the scene
  28218. */
  28219. Scene.prototype.disableGeometryBufferRenderer = function () {
  28220. if (!this._geometryBufferRenderer) {
  28221. return;
  28222. }
  28223. this._geometryBufferRenderer.dispose();
  28224. this._geometryBufferRenderer = null;
  28225. };
  28226. /**
  28227. * Freeze all materials
  28228. * A frozen material will not be updatable but should be faster to render
  28229. */
  28230. Scene.prototype.freezeMaterials = function () {
  28231. for (var i = 0; i < this.materials.length; i++) {
  28232. this.materials[i].freeze();
  28233. }
  28234. };
  28235. /**
  28236. * Unfreeze all materials
  28237. * A frozen material will not be updatable but should be faster to render
  28238. */
  28239. Scene.prototype.unfreezeMaterials = function () {
  28240. for (var i = 0; i < this.materials.length; i++) {
  28241. this.materials[i].unfreeze();
  28242. }
  28243. };
  28244. /**
  28245. * Releases all held ressources
  28246. */
  28247. Scene.prototype.dispose = function () {
  28248. this.beforeRender = null;
  28249. this.afterRender = null;
  28250. this.skeletons = [];
  28251. this.morphTargetManagers = [];
  28252. this.importedMeshesFiles = new Array();
  28253. this.stopAllAnimations();
  28254. this.resetCachedMaterial();
  28255. for (var key in this._depthRenderer) {
  28256. this._depthRenderer[key].dispose();
  28257. }
  28258. if (this._gamepadManager) {
  28259. this._gamepadManager.dispose();
  28260. this._gamepadManager = null;
  28261. }
  28262. // Smart arrays
  28263. if (this.activeCamera) {
  28264. this.activeCamera._activeMeshes.dispose();
  28265. this.activeCamera = null;
  28266. }
  28267. this._activeMeshes.dispose();
  28268. this._renderingManager.dispose();
  28269. this._processedMaterials.dispose();
  28270. this._activeParticleSystems.dispose();
  28271. this._activeSkeletons.dispose();
  28272. this._softwareSkinnedMeshes.dispose();
  28273. this._renderTargets.dispose();
  28274. this._registeredForLateAnimationBindings.dispose();
  28275. if (this._boundingBoxRenderer) {
  28276. this._boundingBoxRenderer.dispose();
  28277. }
  28278. this._meshesForIntersections.dispose();
  28279. this._toBeDisposed.dispose();
  28280. // Abort active requests
  28281. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28282. var request = _a[_i];
  28283. request.abort();
  28284. }
  28285. // Debug layer
  28286. if (this._debugLayer) {
  28287. this._debugLayer.hide();
  28288. }
  28289. // Events
  28290. this.onDisposeObservable.notifyObservers(this);
  28291. this.onDisposeObservable.clear();
  28292. this.onBeforeRenderObservable.clear();
  28293. this.onAfterRenderObservable.clear();
  28294. this.onBeforeRenderTargetsRenderObservable.clear();
  28295. this.onAfterRenderTargetsRenderObservable.clear();
  28296. this.onAfterStepObservable.clear();
  28297. this.onBeforeStepObservable.clear();
  28298. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28299. this.onAfterActiveMeshesEvaluationObservable.clear();
  28300. this.onBeforeParticlesRenderingObservable.clear();
  28301. this.onAfterParticlesRenderingObservable.clear();
  28302. this.onBeforeSpritesRenderingObservable.clear();
  28303. this.onAfterSpritesRenderingObservable.clear();
  28304. this.onBeforeDrawPhaseObservable.clear();
  28305. this.onAfterDrawPhaseObservable.clear();
  28306. this.onBeforePhysicsObservable.clear();
  28307. this.onAfterPhysicsObservable.clear();
  28308. this.onBeforeAnimationsObservable.clear();
  28309. this.onAfterAnimationsObservable.clear();
  28310. this.onDataLoadedObservable.clear();
  28311. this.detachControl();
  28312. // Release sounds & sounds tracks
  28313. if (BABYLON.AudioEngine) {
  28314. this.disposeSounds();
  28315. }
  28316. // VR Helper
  28317. if (this.VRHelper) {
  28318. this.VRHelper.dispose();
  28319. }
  28320. // Detach cameras
  28321. var canvas = this._engine.getRenderingCanvas();
  28322. if (canvas) {
  28323. var index;
  28324. for (index = 0; index < this.cameras.length; index++) {
  28325. this.cameras[index].detachControl(canvas);
  28326. }
  28327. }
  28328. // Release animation groups
  28329. while (this.animationGroups.length) {
  28330. this.animationGroups[0].dispose();
  28331. }
  28332. // Release lights
  28333. while (this.lights.length) {
  28334. this.lights[0].dispose();
  28335. }
  28336. // Release meshes
  28337. while (this.meshes.length) {
  28338. this.meshes[0].dispose(true);
  28339. }
  28340. while (this.transformNodes.length) {
  28341. this.removeTransformNode(this.transformNodes[0]);
  28342. }
  28343. // Release cameras
  28344. while (this.cameras.length) {
  28345. this.cameras[0].dispose();
  28346. }
  28347. // Release materials
  28348. if (this.defaultMaterial) {
  28349. this.defaultMaterial.dispose();
  28350. }
  28351. while (this.multiMaterials.length) {
  28352. this.multiMaterials[0].dispose();
  28353. }
  28354. while (this.materials.length) {
  28355. this.materials[0].dispose();
  28356. }
  28357. // Release particles
  28358. while (this.particleSystems.length) {
  28359. this.particleSystems[0].dispose();
  28360. }
  28361. // Release sprites
  28362. while (this.spriteManagers.length) {
  28363. this.spriteManagers[0].dispose();
  28364. }
  28365. // Release postProcesses
  28366. while (this.postProcesses.length) {
  28367. this.postProcesses[0].dispose();
  28368. }
  28369. // Release layers
  28370. while (this.layers.length) {
  28371. this.layers[0].dispose();
  28372. }
  28373. while (this.effectLayers.length) {
  28374. this.effectLayers[0].dispose();
  28375. }
  28376. // Release textures
  28377. while (this.textures.length) {
  28378. this.textures[0].dispose();
  28379. }
  28380. // Release UBO
  28381. this._sceneUbo.dispose();
  28382. if (this._alternateSceneUbo) {
  28383. this._alternateSceneUbo.dispose();
  28384. }
  28385. // Post-processes
  28386. this.postProcessManager.dispose();
  28387. if (this._postProcessRenderPipelineManager) {
  28388. this._postProcessRenderPipelineManager.dispose();
  28389. }
  28390. // Physics
  28391. if (this._physicsEngine) {
  28392. this.disablePhysicsEngine();
  28393. }
  28394. // Remove from engine
  28395. index = this._engine.scenes.indexOf(this);
  28396. if (index > -1) {
  28397. this._engine.scenes.splice(index, 1);
  28398. }
  28399. this._engine.wipeCaches(true);
  28400. this._isDisposed = true;
  28401. };
  28402. Object.defineProperty(Scene.prototype, "isDisposed", {
  28403. /**
  28404. * Gets if the scene is already disposed
  28405. */
  28406. get: function () {
  28407. return this._isDisposed;
  28408. },
  28409. enumerable: true,
  28410. configurable: true
  28411. });
  28412. /**
  28413. * Releases sounds & soundtracks
  28414. */
  28415. Scene.prototype.disposeSounds = function () {
  28416. if (!this._mainSoundTrack) {
  28417. return;
  28418. }
  28419. this.mainSoundTrack.dispose();
  28420. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28421. this.soundTracks[scIndex].dispose();
  28422. }
  28423. };
  28424. /**
  28425. * Call this function to reduce memory footprint of the scene.
  28426. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28427. */
  28428. Scene.prototype.clearCachedVertexData = function () {
  28429. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28430. var mesh = this.meshes[meshIndex];
  28431. var geometry = mesh.geometry;
  28432. if (geometry) {
  28433. geometry._indices = [];
  28434. for (var vbName in geometry._vertexBuffers) {
  28435. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28436. continue;
  28437. }
  28438. geometry._vertexBuffers[vbName]._buffer._data = null;
  28439. }
  28440. }
  28441. }
  28442. };
  28443. /**
  28444. * This function will remove the local cached buffer data from texture.
  28445. * It will save memory but will prevent the texture from being rebuilt
  28446. */
  28447. Scene.prototype.cleanCachedTextureBuffer = function () {
  28448. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28449. var baseTexture = _a[_i];
  28450. var buffer = baseTexture._buffer;
  28451. if (buffer) {
  28452. baseTexture._buffer = null;
  28453. }
  28454. }
  28455. };
  28456. // Octrees
  28457. /**
  28458. * Get the world extend vectors with an optional filter
  28459. *
  28460. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28461. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28462. */
  28463. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28464. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28465. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28466. filterPredicate = filterPredicate || (function () { return true; });
  28467. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28468. mesh.computeWorldMatrix(true);
  28469. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28470. return;
  28471. }
  28472. var boundingInfo = mesh.getBoundingInfo();
  28473. var minBox = boundingInfo.boundingBox.minimumWorld;
  28474. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28475. BABYLON.Tools.CheckExtends(minBox, min, max);
  28476. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28477. });
  28478. return {
  28479. min: min,
  28480. max: max
  28481. };
  28482. };
  28483. /**
  28484. * Creates or updates the octree used to boost selection (picking)
  28485. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28486. * @param maxCapacity defines the maximum capacity per leaf
  28487. * @param maxDepth defines the maximum depth of the octree
  28488. * @returns an octree of AbstractMesh
  28489. */
  28490. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28491. if (maxCapacity === void 0) { maxCapacity = 64; }
  28492. if (maxDepth === void 0) { maxDepth = 2; }
  28493. if (!this._selectionOctree) {
  28494. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28495. }
  28496. var worldExtends = this.getWorldExtends();
  28497. // Update octree
  28498. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28499. return this._selectionOctree;
  28500. };
  28501. // Picking
  28502. /**
  28503. * Creates a ray that can be used to pick in the scene
  28504. * @param x defines the x coordinate of the origin (on-screen)
  28505. * @param y defines the y coordinate of the origin (on-screen)
  28506. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28507. * @param camera defines the camera to use for the picking
  28508. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28509. * @returns a Ray
  28510. */
  28511. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28512. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28513. var result = BABYLON.Ray.Zero();
  28514. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28515. return result;
  28516. };
  28517. /**
  28518. * Creates a ray that can be used to pick in the scene
  28519. * @param x defines the x coordinate of the origin (on-screen)
  28520. * @param y defines the y coordinate of the origin (on-screen)
  28521. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28522. * @param result defines the ray where to store the picking ray
  28523. * @param camera defines the camera to use for the picking
  28524. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28525. * @returns the current scene
  28526. */
  28527. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28528. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28529. var engine = this._engine;
  28530. if (!camera) {
  28531. if (!this.activeCamera)
  28532. throw new Error("Active camera not set");
  28533. camera = this.activeCamera;
  28534. }
  28535. var cameraViewport = camera.viewport;
  28536. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28537. // Moving coordinates to local viewport world
  28538. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28539. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28540. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28541. return this;
  28542. };
  28543. /**
  28544. * Creates a ray that can be used to pick in the scene
  28545. * @param x defines the x coordinate of the origin (on-screen)
  28546. * @param y defines the y coordinate of the origin (on-screen)
  28547. * @param camera defines the camera to use for the picking
  28548. * @returns a Ray
  28549. */
  28550. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28551. var result = BABYLON.Ray.Zero();
  28552. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28553. return result;
  28554. };
  28555. /**
  28556. * Creates a ray that can be used to pick in the scene
  28557. * @param x defines the x coordinate of the origin (on-screen)
  28558. * @param y defines the y coordinate of the origin (on-screen)
  28559. * @param result defines the ray where to store the picking ray
  28560. * @param camera defines the camera to use for the picking
  28561. * @returns the current scene
  28562. */
  28563. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28564. if (!BABYLON.PickingInfo) {
  28565. return this;
  28566. }
  28567. var engine = this._engine;
  28568. if (!camera) {
  28569. if (!this.activeCamera)
  28570. throw new Error("Active camera not set");
  28571. camera = this.activeCamera;
  28572. }
  28573. var cameraViewport = camera.viewport;
  28574. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28575. var identity = BABYLON.Matrix.Identity();
  28576. // Moving coordinates to local viewport world
  28577. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28578. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28579. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28580. return this;
  28581. };
  28582. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28583. if (!BABYLON.PickingInfo) {
  28584. return null;
  28585. }
  28586. var pickingInfo = null;
  28587. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28588. var mesh = this.meshes[meshIndex];
  28589. if (predicate) {
  28590. if (!predicate(mesh)) {
  28591. continue;
  28592. }
  28593. }
  28594. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28595. continue;
  28596. }
  28597. var world = mesh.getWorldMatrix();
  28598. var ray = rayFunction(world);
  28599. var result = mesh.intersects(ray, fastCheck);
  28600. if (!result || !result.hit)
  28601. continue;
  28602. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28603. continue;
  28604. pickingInfo = result;
  28605. if (fastCheck) {
  28606. break;
  28607. }
  28608. }
  28609. return pickingInfo || new BABYLON.PickingInfo();
  28610. };
  28611. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28612. if (!BABYLON.PickingInfo) {
  28613. return null;
  28614. }
  28615. var pickingInfos = new Array();
  28616. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28617. var mesh = this.meshes[meshIndex];
  28618. if (predicate) {
  28619. if (!predicate(mesh)) {
  28620. continue;
  28621. }
  28622. }
  28623. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28624. continue;
  28625. }
  28626. var world = mesh.getWorldMatrix();
  28627. var ray = rayFunction(world);
  28628. var result = mesh.intersects(ray, false);
  28629. if (!result || !result.hit)
  28630. continue;
  28631. pickingInfos.push(result);
  28632. }
  28633. return pickingInfos;
  28634. };
  28635. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28636. if (!BABYLON.PickingInfo) {
  28637. return null;
  28638. }
  28639. var pickingInfo = null;
  28640. if (!camera) {
  28641. if (!this.activeCamera) {
  28642. return null;
  28643. }
  28644. camera = this.activeCamera;
  28645. }
  28646. if (this.spriteManagers.length > 0) {
  28647. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28648. var spriteManager = this.spriteManagers[spriteIndex];
  28649. if (!spriteManager.isPickable) {
  28650. continue;
  28651. }
  28652. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28653. if (!result || !result.hit)
  28654. continue;
  28655. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28656. continue;
  28657. pickingInfo = result;
  28658. if (fastCheck) {
  28659. break;
  28660. }
  28661. }
  28662. }
  28663. return pickingInfo || new BABYLON.PickingInfo();
  28664. };
  28665. /** Launch a ray to try to pick a mesh in the scene
  28666. * @param x position on screen
  28667. * @param y position on screen
  28668. * @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
  28669. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28670. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28671. * @returns a PickingInfo
  28672. */
  28673. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28674. var _this = this;
  28675. if (!BABYLON.PickingInfo) {
  28676. return null;
  28677. }
  28678. var result = this._internalPick(function (world) {
  28679. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28680. return _this._tempPickingRay;
  28681. }, predicate, fastCheck);
  28682. if (result) {
  28683. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28684. }
  28685. return result;
  28686. };
  28687. /** Launch a ray to try to pick a sprite in the scene
  28688. * @param x position on screen
  28689. * @param y position on screen
  28690. * @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
  28691. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28692. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28693. * @returns a PickingInfo
  28694. */
  28695. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28696. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28697. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28698. };
  28699. /** Use the given ray to pick a mesh in the scene
  28700. * @param ray The ray to use to pick meshes
  28701. * @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
  28702. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28703. * @returns a PickingInfo
  28704. */
  28705. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28706. var _this = this;
  28707. var result = this._internalPick(function (world) {
  28708. if (!_this._pickWithRayInverseMatrix) {
  28709. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28710. }
  28711. world.invertToRef(_this._pickWithRayInverseMatrix);
  28712. if (!_this._cachedRayForTransform) {
  28713. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28714. }
  28715. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28716. return _this._cachedRayForTransform;
  28717. }, predicate, fastCheck);
  28718. if (result) {
  28719. result.ray = ray;
  28720. }
  28721. return result;
  28722. };
  28723. /**
  28724. * Launch a ray to try to pick a mesh in the scene
  28725. * @param x X position on screen
  28726. * @param y Y position on screen
  28727. * @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
  28728. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28729. * @returns an array of PickingInfo
  28730. */
  28731. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28732. var _this = this;
  28733. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28734. };
  28735. /**
  28736. * Launch a ray to try to pick a mesh in the scene
  28737. * @param ray Ray to use
  28738. * @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
  28739. * @returns an array of PickingInfo
  28740. */
  28741. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28742. var _this = this;
  28743. return this._internalMultiPick(function (world) {
  28744. if (!_this._pickWithRayInverseMatrix) {
  28745. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28746. }
  28747. world.invertToRef(_this._pickWithRayInverseMatrix);
  28748. if (!_this._cachedRayForTransform) {
  28749. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28750. }
  28751. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28752. return _this._cachedRayForTransform;
  28753. }, predicate);
  28754. };
  28755. /**
  28756. * Force the value of meshUnderPointer
  28757. * @param mesh defines the mesh to use
  28758. */
  28759. Scene.prototype.setPointerOverMesh = function (mesh) {
  28760. if (this._pointerOverMesh === mesh) {
  28761. return;
  28762. }
  28763. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28764. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28765. }
  28766. this._pointerOverMesh = mesh;
  28767. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28768. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28769. }
  28770. };
  28771. /**
  28772. * Gets the mesh under the pointer
  28773. * @returns a Mesh or null if no mesh is under the pointer
  28774. */
  28775. Scene.prototype.getPointerOverMesh = function () {
  28776. return this._pointerOverMesh;
  28777. };
  28778. /**
  28779. * Force the sprite under the pointer
  28780. * @param sprite defines the sprite to use
  28781. */
  28782. Scene.prototype.setPointerOverSprite = function (sprite) {
  28783. if (this._pointerOverSprite === sprite) {
  28784. return;
  28785. }
  28786. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28787. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28788. }
  28789. this._pointerOverSprite = sprite;
  28790. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28791. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28792. }
  28793. };
  28794. /**
  28795. * Gets the sprite under the pointer
  28796. * @returns a Sprite or null if no sprite is under the pointer
  28797. */
  28798. Scene.prototype.getPointerOverSprite = function () {
  28799. return this._pointerOverSprite;
  28800. };
  28801. // Physics
  28802. /**
  28803. * Gets the current physics engine
  28804. * @returns a PhysicsEngine or null if none attached
  28805. */
  28806. Scene.prototype.getPhysicsEngine = function () {
  28807. return this._physicsEngine;
  28808. };
  28809. /**
  28810. * Enables physics to the current scene
  28811. * @param gravity defines the scene's gravity for the physics engine
  28812. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28813. * @return a boolean indicating if the physics engine was initialized
  28814. */
  28815. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28816. if (gravity === void 0) { gravity = null; }
  28817. if (this._physicsEngine) {
  28818. return true;
  28819. }
  28820. try {
  28821. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28822. return true;
  28823. }
  28824. catch (e) {
  28825. BABYLON.Tools.Error(e.message);
  28826. return false;
  28827. }
  28828. };
  28829. /**
  28830. * Disables and disposes the physics engine associated with the scene
  28831. */
  28832. Scene.prototype.disablePhysicsEngine = function () {
  28833. if (!this._physicsEngine) {
  28834. return;
  28835. }
  28836. this._physicsEngine.dispose();
  28837. this._physicsEngine = null;
  28838. };
  28839. /**
  28840. * Gets a boolean indicating if there is an active physics engine
  28841. * @returns a boolean indicating if there is an active physics engine
  28842. */
  28843. Scene.prototype.isPhysicsEnabled = function () {
  28844. return this._physicsEngine !== undefined;
  28845. };
  28846. /**
  28847. * Deletes a physics compound impostor
  28848. * @param compound defines the compound to delete
  28849. */
  28850. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28851. var mesh = compound.parts[0].mesh;
  28852. if (mesh.physicsImpostor) {
  28853. mesh.physicsImpostor.dispose( /*true*/);
  28854. mesh.physicsImpostor = null;
  28855. }
  28856. };
  28857. // Misc.
  28858. /** @hidden */
  28859. Scene.prototype._rebuildGeometries = function () {
  28860. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28861. var geometry = _a[_i];
  28862. geometry._rebuild();
  28863. }
  28864. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28865. var mesh = _c[_b];
  28866. mesh._rebuild();
  28867. }
  28868. if (this.postProcessManager) {
  28869. this.postProcessManager._rebuild();
  28870. }
  28871. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28872. var layer = _e[_d];
  28873. layer._rebuild();
  28874. }
  28875. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28876. var effectLayer = _g[_f];
  28877. effectLayer._rebuild();
  28878. }
  28879. if (this._boundingBoxRenderer) {
  28880. this._boundingBoxRenderer._rebuild();
  28881. }
  28882. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28883. var system = _j[_h];
  28884. system.rebuild();
  28885. }
  28886. if (this._postProcessRenderPipelineManager) {
  28887. this._postProcessRenderPipelineManager._rebuild();
  28888. }
  28889. };
  28890. /** @hidden */
  28891. Scene.prototype._rebuildTextures = function () {
  28892. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28893. var texture = _a[_i];
  28894. texture._rebuild();
  28895. }
  28896. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28897. };
  28898. /**
  28899. * Creates a default light for the scene.
  28900. * @param replace Whether to replace the existing lights in the scene.
  28901. */
  28902. Scene.prototype.createDefaultLight = function (replace) {
  28903. if (replace === void 0) { replace = false; }
  28904. // Dispose existing light in replace mode.
  28905. if (replace) {
  28906. if (this.lights) {
  28907. for (var i = 0; i < this.lights.length; i++) {
  28908. this.lights[i].dispose();
  28909. }
  28910. }
  28911. }
  28912. // Light
  28913. if (this.lights.length === 0) {
  28914. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28915. }
  28916. };
  28917. /**
  28918. * Creates a default camera for the scene.
  28919. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28920. * @param replace Whether to replace the existing active camera in the scene.
  28921. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28922. */
  28923. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28924. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28925. if (replace === void 0) { replace = false; }
  28926. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28927. // Dispose existing camera in replace mode.
  28928. if (replace) {
  28929. if (this.activeCamera) {
  28930. this.activeCamera.dispose();
  28931. this.activeCamera = null;
  28932. }
  28933. }
  28934. // Camera
  28935. if (!this.activeCamera) {
  28936. var worldExtends = this.getWorldExtends();
  28937. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28938. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28939. var camera;
  28940. var radius = worldSize.length() * 1.5;
  28941. // empty scene scenario!
  28942. if (!isFinite(radius)) {
  28943. radius = 1;
  28944. worldCenter.copyFromFloats(0, 0, 0);
  28945. }
  28946. if (createArcRotateCamera) {
  28947. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28948. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28949. arcRotateCamera.wheelPrecision = 100 / radius;
  28950. camera = arcRotateCamera;
  28951. }
  28952. else {
  28953. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28954. freeCamera.setTarget(worldCenter);
  28955. camera = freeCamera;
  28956. }
  28957. camera.minZ = radius * 0.01;
  28958. camera.maxZ = radius * 1000;
  28959. camera.speed = radius * 0.2;
  28960. this.activeCamera = camera;
  28961. var canvas = this.getEngine().getRenderingCanvas();
  28962. if (attachCameraControls && canvas) {
  28963. camera.attachControl(canvas);
  28964. }
  28965. }
  28966. };
  28967. /**
  28968. * Creates a default camera and a default light
  28969. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28970. * @param replace defines if the camera and/or light will replace the existing ones
  28971. * @param attachCameraControls defines if attachControl will be called on the new camera
  28972. */
  28973. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28974. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28975. if (replace === void 0) { replace = false; }
  28976. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28977. this.createDefaultLight(replace);
  28978. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28979. };
  28980. /**
  28981. * Creates a new sky box
  28982. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28983. * @param environmentTexture defines the texture to use as environment texture
  28984. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28985. * @param scale defines the overall scale of the skybox
  28986. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28987. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28988. * @returns a new mesh holding the sky box
  28989. */
  28990. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28991. if (pbr === void 0) { pbr = false; }
  28992. if (scale === void 0) { scale = 1000; }
  28993. if (blur === void 0) { blur = 0; }
  28994. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28995. if (!environmentTexture) {
  28996. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28997. return null;
  28998. }
  28999. if (setGlobalEnvTexture) {
  29000. if (environmentTexture) {
  29001. this.environmentTexture = environmentTexture;
  29002. }
  29003. }
  29004. // Skybox
  29005. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29006. if (pbr) {
  29007. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29008. hdrSkyboxMaterial.backFaceCulling = false;
  29009. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29010. if (hdrSkyboxMaterial.reflectionTexture) {
  29011. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29012. }
  29013. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29014. hdrSkyboxMaterial.disableLighting = true;
  29015. hdrSkyboxMaterial.twoSidedLighting = true;
  29016. hdrSkybox.infiniteDistance = true;
  29017. hdrSkybox.material = hdrSkyboxMaterial;
  29018. }
  29019. else {
  29020. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29021. skyboxMaterial.backFaceCulling = false;
  29022. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29023. if (skyboxMaterial.reflectionTexture) {
  29024. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29025. }
  29026. skyboxMaterial.disableLighting = true;
  29027. hdrSkybox.infiniteDistance = true;
  29028. hdrSkybox.material = skyboxMaterial;
  29029. }
  29030. return hdrSkybox;
  29031. };
  29032. /**
  29033. * Creates a new environment
  29034. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29035. * @param options defines the options you can use to configure the environment
  29036. * @returns the new EnvironmentHelper
  29037. */
  29038. Scene.prototype.createDefaultEnvironment = function (options) {
  29039. if (BABYLON.EnvironmentHelper) {
  29040. return new BABYLON.EnvironmentHelper(options, this);
  29041. }
  29042. return null;
  29043. };
  29044. /**
  29045. * Creates a new VREXperienceHelper
  29046. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29047. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29048. * @returns a new VREXperienceHelper
  29049. */
  29050. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29051. if (webVROptions === void 0) { webVROptions = {}; }
  29052. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29053. };
  29054. // Tags
  29055. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29056. if (tagsQuery === undefined) {
  29057. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29058. return list;
  29059. }
  29060. var listByTags = [];
  29061. forEach = forEach || (function (item) { return; });
  29062. for (var i in list) {
  29063. var item = list[i];
  29064. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29065. listByTags.push(item);
  29066. forEach(item);
  29067. }
  29068. }
  29069. return listByTags;
  29070. };
  29071. /**
  29072. * Get a list of meshes by tags
  29073. * @param tagsQuery defines the tags query to use
  29074. * @param forEach defines a predicate used to filter results
  29075. * @returns an array of Mesh
  29076. */
  29077. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29078. return this._getByTags(this.meshes, tagsQuery, forEach);
  29079. };
  29080. /**
  29081. * Get a list of cameras by tags
  29082. * @param tagsQuery defines the tags query to use
  29083. * @param forEach defines a predicate used to filter results
  29084. * @returns an array of Camera
  29085. */
  29086. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29087. return this._getByTags(this.cameras, tagsQuery, forEach);
  29088. };
  29089. /**
  29090. * Get a list of lights by tags
  29091. * @param tagsQuery defines the tags query to use
  29092. * @param forEach defines a predicate used to filter results
  29093. * @returns an array of Light
  29094. */
  29095. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29096. return this._getByTags(this.lights, tagsQuery, forEach);
  29097. };
  29098. /**
  29099. * Get a list of materials by tags
  29100. * @param tagsQuery defines the tags query to use
  29101. * @param forEach defines a predicate used to filter results
  29102. * @returns an array of Material
  29103. */
  29104. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29105. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29106. };
  29107. /**
  29108. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29109. * This allowed control for front to back rendering or reversly depending of the special needs.
  29110. *
  29111. * @param renderingGroupId The rendering group id corresponding to its index
  29112. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29113. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29114. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29115. */
  29116. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29117. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29118. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29119. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29120. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29121. };
  29122. /**
  29123. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29124. *
  29125. * @param renderingGroupId The rendering group id corresponding to its index
  29126. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29127. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29128. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29129. */
  29130. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29131. if (depth === void 0) { depth = true; }
  29132. if (stencil === void 0) { stencil = true; }
  29133. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29134. };
  29135. /**
  29136. * Will flag all materials as dirty to trigger new shader compilation
  29137. * @param flag defines the flag used to specify which material part must be marked as dirty
  29138. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29139. */
  29140. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29141. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29142. var material = _a[_i];
  29143. if (predicate && !predicate(material)) {
  29144. continue;
  29145. }
  29146. material.markAsDirty(flag);
  29147. }
  29148. };
  29149. /** @hidden */
  29150. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29151. var _this = this;
  29152. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29153. this._activeRequests.push(request);
  29154. request.onCompleteObservable.add(function (request) {
  29155. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29156. });
  29157. return request;
  29158. };
  29159. /** @hidden */
  29160. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29161. var _this = this;
  29162. return new Promise(function (resolve, reject) {
  29163. _this._loadFile(url, function (data) {
  29164. resolve(data);
  29165. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29166. reject(exception);
  29167. });
  29168. });
  29169. };
  29170. // Statics
  29171. Scene._FOGMODE_NONE = 0;
  29172. Scene._FOGMODE_EXP = 1;
  29173. Scene._FOGMODE_EXP2 = 2;
  29174. Scene._FOGMODE_LINEAR = 3;
  29175. Scene._uniqueIdCounter = 0;
  29176. /**
  29177. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29178. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29179. */
  29180. Scene.MinDeltaTime = 1.0;
  29181. /**
  29182. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29183. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29184. */
  29185. Scene.MaxDeltaTime = 1000.0;
  29186. /** The distance in pixel that you have to move to prevent some events */
  29187. Scene.DragMovementThreshold = 10; // in pixels
  29188. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29189. Scene.LongPressDelay = 500; // in milliseconds
  29190. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29191. Scene.DoubleClickDelay = 300; // in milliseconds
  29192. /** If you need to check double click without raising a single click at first click, enable this flag */
  29193. Scene.ExclusiveDoubleClickMode = false;
  29194. return Scene;
  29195. }());
  29196. BABYLON.Scene = Scene;
  29197. })(BABYLON || (BABYLON = {}));
  29198. //# sourceMappingURL=babylon.scene.js.map
  29199. var BABYLON;
  29200. (function (BABYLON) {
  29201. /**
  29202. * Set of assets to keep when moving a scene into an asset container.
  29203. */
  29204. var KeepAssets = /** @class */ (function () {
  29205. function KeepAssets() {
  29206. /**
  29207. * Cameras to keep.
  29208. */
  29209. this.cameras = new Array();
  29210. /**
  29211. * Lights to keep.
  29212. */
  29213. this.lights = new Array();
  29214. /**
  29215. * Meshes to keep.
  29216. */
  29217. this.meshes = new Array();
  29218. /**
  29219. * Skeletons to keep.
  29220. */
  29221. this.skeletons = new Array();
  29222. /**
  29223. * ParticleSystems to keep.
  29224. */
  29225. this.particleSystems = new Array();
  29226. /**
  29227. * Animations to keep.
  29228. */
  29229. this.animations = new Array();
  29230. /**
  29231. * AnimationGroups to keep.
  29232. */
  29233. this.animationGroups = new Array();
  29234. /**
  29235. * MultiMaterials to keep.
  29236. */
  29237. this.multiMaterials = new Array();
  29238. /**
  29239. * Materials to keep.
  29240. */
  29241. this.materials = new Array();
  29242. /**
  29243. * MorphTargetManagers to keep.
  29244. */
  29245. this.morphTargetManagers = new Array();
  29246. /**
  29247. * Geometries to keep.
  29248. */
  29249. this.geometries = new Array();
  29250. /**
  29251. * TransformNodes to keep.
  29252. */
  29253. this.transformNodes = new Array();
  29254. /**
  29255. * LensFlareSystems to keep.
  29256. */
  29257. this.lensFlareSystems = new Array();
  29258. /**
  29259. * ShadowGenerators to keep.
  29260. */
  29261. this.shadowGenerators = new Array();
  29262. /**
  29263. * ActionManagers to keep.
  29264. */
  29265. this.actionManagers = new Array();
  29266. /**
  29267. * Sounds to keep.
  29268. */
  29269. this.sounds = new Array();
  29270. /**
  29271. * Textures to keep.
  29272. */
  29273. this.textures = new Array();
  29274. /**
  29275. * Effect layers to keep.
  29276. */
  29277. this.effectLayers = new Array();
  29278. }
  29279. return KeepAssets;
  29280. }());
  29281. BABYLON.KeepAssets = KeepAssets;
  29282. /**
  29283. * Container with a set of assets that can be added or removed from a scene.
  29284. */
  29285. var AssetContainer = /** @class */ (function () {
  29286. /**
  29287. * Instantiates an AssetContainer.
  29288. * @param scene The scene the AssetContainer belongs to.
  29289. */
  29290. function AssetContainer(scene) {
  29291. // Objects
  29292. /**
  29293. * Cameras populated in the container.
  29294. */
  29295. this.cameras = new Array();
  29296. /**
  29297. * Lights populated in the container.
  29298. */
  29299. this.lights = new Array();
  29300. /**
  29301. * Meshes populated in the container.
  29302. */
  29303. this.meshes = new Array();
  29304. /**
  29305. * Skeletons populated in the container.
  29306. */
  29307. this.skeletons = new Array();
  29308. /**
  29309. * ParticleSystems populated in the container.
  29310. */
  29311. this.particleSystems = new Array();
  29312. /**
  29313. * Animations populated in the container.
  29314. */
  29315. this.animations = new Array();
  29316. /**
  29317. * AnimationGroups populated in the container.
  29318. */
  29319. this.animationGroups = new Array();
  29320. /**
  29321. * MultiMaterials populated in the container.
  29322. */
  29323. this.multiMaterials = new Array();
  29324. /**
  29325. * Materials populated in the container.
  29326. */
  29327. this.materials = new Array();
  29328. /**
  29329. * MorphTargetManagers populated in the container.
  29330. */
  29331. this.morphTargetManagers = new Array();
  29332. /**
  29333. * Geometries populated in the container.
  29334. */
  29335. this.geometries = new Array();
  29336. /**
  29337. * TransformNodes populated in the container.
  29338. */
  29339. this.transformNodes = new Array();
  29340. /**
  29341. * LensFlareSystems populated in the container.
  29342. */
  29343. this.lensFlareSystems = new Array();
  29344. /**
  29345. * ShadowGenerators populated in the container.
  29346. */
  29347. this.shadowGenerators = new Array();
  29348. /**
  29349. * ActionManagers populated in the container.
  29350. */
  29351. this.actionManagers = new Array();
  29352. /**
  29353. * Sounds populated in the container.
  29354. */
  29355. this.sounds = new Array();
  29356. /**
  29357. * Textures populated in the container.
  29358. */
  29359. this.textures = new Array();
  29360. /**
  29361. * Effect layers populated in the container.
  29362. */
  29363. this.effectLayers = new Array();
  29364. this.scene = scene;
  29365. }
  29366. /**
  29367. * Adds all the assets from the container to the scene.
  29368. */
  29369. AssetContainer.prototype.addAllToScene = function () {
  29370. var _this = this;
  29371. this.cameras.forEach(function (o) {
  29372. _this.scene.addCamera(o);
  29373. });
  29374. this.lights.forEach(function (o) {
  29375. _this.scene.addLight(o);
  29376. });
  29377. this.meshes.forEach(function (o) {
  29378. _this.scene.addMesh(o);
  29379. });
  29380. this.skeletons.forEach(function (o) {
  29381. _this.scene.addSkeleton(o);
  29382. });
  29383. this.particleSystems.forEach(function (o) {
  29384. _this.scene.addParticleSystem(o);
  29385. });
  29386. this.animations.forEach(function (o) {
  29387. _this.scene.addAnimation(o);
  29388. });
  29389. this.animationGroups.forEach(function (o) {
  29390. _this.scene.addAnimationGroup(o);
  29391. });
  29392. this.multiMaterials.forEach(function (o) {
  29393. _this.scene.addMultiMaterial(o);
  29394. });
  29395. this.materials.forEach(function (o) {
  29396. _this.scene.addMaterial(o);
  29397. });
  29398. this.morphTargetManagers.forEach(function (o) {
  29399. _this.scene.addMorphTargetManager(o);
  29400. });
  29401. this.geometries.forEach(function (o) {
  29402. _this.scene.addGeometry(o);
  29403. });
  29404. this.transformNodes.forEach(function (o) {
  29405. _this.scene.addTransformNode(o);
  29406. });
  29407. this.lensFlareSystems.forEach(function (o) {
  29408. _this.scene.addLensFlareSystem(o);
  29409. });
  29410. this.actionManagers.forEach(function (o) {
  29411. _this.scene.addActionManager(o);
  29412. });
  29413. this.sounds.forEach(function (o) {
  29414. o.play();
  29415. o.autoplay = true;
  29416. _this.scene.mainSoundTrack.AddSound(o);
  29417. });
  29418. this.textures.forEach(function (o) {
  29419. _this.scene.addTexture(o);
  29420. });
  29421. this.effectLayers.forEach(function (o) {
  29422. _this.scene.addEffectLayer(o);
  29423. });
  29424. };
  29425. /**
  29426. * Removes all the assets in the container from the scene
  29427. */
  29428. AssetContainer.prototype.removeAllFromScene = function () {
  29429. var _this = this;
  29430. this.cameras.forEach(function (o) {
  29431. _this.scene.removeCamera(o);
  29432. });
  29433. this.lights.forEach(function (o) {
  29434. _this.scene.removeLight(o);
  29435. });
  29436. this.meshes.forEach(function (o) {
  29437. _this.scene.removeMesh(o);
  29438. });
  29439. this.skeletons.forEach(function (o) {
  29440. _this.scene.removeSkeleton(o);
  29441. });
  29442. this.particleSystems.forEach(function (o) {
  29443. _this.scene.removeParticleSystem(o);
  29444. });
  29445. this.animations.forEach(function (o) {
  29446. _this.scene.removeAnimation(o);
  29447. });
  29448. this.animationGroups.forEach(function (o) {
  29449. _this.scene.removeAnimationGroup(o);
  29450. });
  29451. this.multiMaterials.forEach(function (o) {
  29452. _this.scene.removeMultiMaterial(o);
  29453. });
  29454. this.materials.forEach(function (o) {
  29455. _this.scene.removeMaterial(o);
  29456. });
  29457. this.morphTargetManagers.forEach(function (o) {
  29458. _this.scene.removeMorphTargetManager(o);
  29459. });
  29460. this.geometries.forEach(function (o) {
  29461. _this.scene.removeGeometry(o);
  29462. });
  29463. this.transformNodes.forEach(function (o) {
  29464. _this.scene.removeTransformNode(o);
  29465. });
  29466. this.lensFlareSystems.forEach(function (o) {
  29467. _this.scene.removeLensFlareSystem(o);
  29468. });
  29469. this.actionManagers.forEach(function (o) {
  29470. _this.scene.removeActionManager(o);
  29471. });
  29472. this.sounds.forEach(function (o) {
  29473. o.stop();
  29474. o.autoplay = false;
  29475. _this.scene.mainSoundTrack.RemoveSound(o);
  29476. });
  29477. this.textures.forEach(function (o) {
  29478. _this.scene.removeTexture(o);
  29479. });
  29480. this.effectLayers.forEach(function (o) {
  29481. _this.scene.removeEffectLayer(o);
  29482. });
  29483. };
  29484. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29485. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29486. var asset = sourceAssets_1[_i];
  29487. var move = true;
  29488. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29489. var keepAsset = keepAssets_1[_a];
  29490. if (asset === keepAsset) {
  29491. move = false;
  29492. break;
  29493. }
  29494. }
  29495. if (move) {
  29496. targetAssets.push(asset);
  29497. }
  29498. }
  29499. };
  29500. /**
  29501. * Removes all the assets contained in the scene and adds them to the container.
  29502. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29503. */
  29504. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29505. if (keepAssets === undefined) {
  29506. keepAssets = new KeepAssets();
  29507. }
  29508. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29509. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29510. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29511. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29512. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29513. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29514. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29515. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29516. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29517. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29518. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29519. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29520. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29521. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29522. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29523. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29524. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29525. this.removeAllFromScene();
  29526. };
  29527. /**
  29528. * 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.
  29529. * @returns the root mesh
  29530. */
  29531. AssetContainer.prototype.createRootMesh = function () {
  29532. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29533. this.meshes.forEach(function (m) {
  29534. if (!m.parent) {
  29535. rootMesh.addChild(m);
  29536. }
  29537. });
  29538. this.meshes.unshift(rootMesh);
  29539. return rootMesh;
  29540. };
  29541. return AssetContainer;
  29542. }());
  29543. BABYLON.AssetContainer = AssetContainer;
  29544. })(BABYLON || (BABYLON = {}));
  29545. //# sourceMappingURL=babylon.assetContainer.js.map
  29546. var BABYLON;
  29547. (function (BABYLON) {
  29548. var Buffer = /** @class */ (function () {
  29549. /**
  29550. * Constructor
  29551. * @param engine the engine
  29552. * @param data the data to use for this buffer
  29553. * @param updatable whether the data is updatable
  29554. * @param stride the stride (optional)
  29555. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29556. * @param instanced whether the buffer is instanced (optional)
  29557. * @param useBytes set to true if the stride in in bytes (optional)
  29558. */
  29559. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29560. if (stride === void 0) { stride = 0; }
  29561. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29562. if (instanced === void 0) { instanced = false; }
  29563. if (useBytes === void 0) { useBytes = false; }
  29564. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29565. this._engine = engine.getScene().getEngine();
  29566. }
  29567. else {
  29568. this._engine = engine;
  29569. }
  29570. this._updatable = updatable;
  29571. this._instanced = instanced;
  29572. this._data = data;
  29573. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29574. if (!postponeInternalCreation) { // by default
  29575. this.create();
  29576. }
  29577. }
  29578. /**
  29579. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29580. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29581. * @param offset defines offset in the buffer (0 by default)
  29582. * @param size defines the size in floats of attributes (position is 3 for instance)
  29583. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29584. * @param instanced defines if the vertex buffer contains indexed data
  29585. * @param useBytes defines if the offset and stride are in bytes
  29586. * @returns the new vertex buffer
  29587. */
  29588. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29589. if (useBytes === void 0) { useBytes = false; }
  29590. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29591. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29592. // a lot of these parameters are ignored as they are overriden by the buffer
  29593. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29594. };
  29595. // Properties
  29596. Buffer.prototype.isUpdatable = function () {
  29597. return this._updatable;
  29598. };
  29599. Buffer.prototype.getData = function () {
  29600. return this._data;
  29601. };
  29602. Buffer.prototype.getBuffer = function () {
  29603. return this._buffer;
  29604. };
  29605. /**
  29606. * Gets the stride in float32 units (i.e. byte stride / 4).
  29607. * May not be an integer if the byte stride is not divisible by 4.
  29608. * DEPRECATED. Use byteStride instead.
  29609. * @returns the stride in float32 units
  29610. */
  29611. Buffer.prototype.getStrideSize = function () {
  29612. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29613. };
  29614. // Methods
  29615. Buffer.prototype.create = function (data) {
  29616. if (data === void 0) { data = null; }
  29617. if (!data && this._buffer) {
  29618. return; // nothing to do
  29619. }
  29620. data = data || this._data;
  29621. if (!data) {
  29622. return;
  29623. }
  29624. if (!this._buffer) { // create buffer
  29625. if (this._updatable) {
  29626. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29627. this._data = data;
  29628. }
  29629. else {
  29630. this._buffer = this._engine.createVertexBuffer(data);
  29631. }
  29632. }
  29633. else if (this._updatable) { // update buffer
  29634. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29635. this._data = data;
  29636. }
  29637. };
  29638. Buffer.prototype._rebuild = function () {
  29639. this._buffer = null;
  29640. this.create(this._data);
  29641. };
  29642. Buffer.prototype.update = function (data) {
  29643. this.create(data);
  29644. };
  29645. /**
  29646. * Updates the data directly.
  29647. * @param data the new data
  29648. * @param offset the new offset
  29649. * @param vertexCount the vertex count (optional)
  29650. * @param useBytes set to true if the offset is in bytes
  29651. */
  29652. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29653. if (useBytes === void 0) { useBytes = false; }
  29654. if (!this._buffer) {
  29655. return;
  29656. }
  29657. if (this._updatable) { // update buffer
  29658. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29659. this._data = null;
  29660. }
  29661. };
  29662. Buffer.prototype.dispose = function () {
  29663. if (!this._buffer) {
  29664. return;
  29665. }
  29666. if (this._engine._releaseBuffer(this._buffer)) {
  29667. this._buffer = null;
  29668. }
  29669. };
  29670. return Buffer;
  29671. }());
  29672. BABYLON.Buffer = Buffer;
  29673. })(BABYLON || (BABYLON = {}));
  29674. //# sourceMappingURL=babylon.buffer.js.map
  29675. var BABYLON;
  29676. (function (BABYLON) {
  29677. var VertexBuffer = /** @class */ (function () {
  29678. /**
  29679. * Constructor
  29680. * @param engine the engine
  29681. * @param data the data to use for this vertex buffer
  29682. * @param kind the vertex buffer kind
  29683. * @param updatable whether the data is updatable
  29684. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29685. * @param stride the stride (optional)
  29686. * @param instanced whether the buffer is instanced (optional)
  29687. * @param offset the offset of the data (optional)
  29688. * @param size the number of components (optional)
  29689. * @param type the type of the component (optional)
  29690. * @param normalized whether the data contains normalized data (optional)
  29691. * @param useBytes set to true if stride and offset are in bytes (optional)
  29692. */
  29693. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29694. if (normalized === void 0) { normalized = false; }
  29695. if (useBytes === void 0) { useBytes = false; }
  29696. if (data instanceof BABYLON.Buffer) {
  29697. this._buffer = data;
  29698. this._ownsBuffer = false;
  29699. }
  29700. else {
  29701. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29702. this._ownsBuffer = true;
  29703. }
  29704. this._kind = kind;
  29705. if (type == undefined) {
  29706. var data_1 = this.getData();
  29707. this.type = VertexBuffer.FLOAT;
  29708. if (data_1 instanceof Int8Array)
  29709. this.type = VertexBuffer.BYTE;
  29710. else if (data_1 instanceof Uint8Array)
  29711. this.type = VertexBuffer.UNSIGNED_BYTE;
  29712. else if (data_1 instanceof Int16Array)
  29713. this.type = VertexBuffer.SHORT;
  29714. else if (data_1 instanceof Uint16Array)
  29715. this.type = VertexBuffer.UNSIGNED_SHORT;
  29716. else if (data_1 instanceof Int32Array)
  29717. this.type = VertexBuffer.INT;
  29718. else if (data_1 instanceof Uint32Array)
  29719. this.type = VertexBuffer.UNSIGNED_INT;
  29720. }
  29721. else {
  29722. this.type = type;
  29723. }
  29724. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29725. if (useBytes) {
  29726. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29727. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29728. this.byteOffset = offset || 0;
  29729. }
  29730. else {
  29731. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29732. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29733. this.byteOffset = (offset || 0) * typeByteLength;
  29734. }
  29735. this.normalized = normalized;
  29736. this._instanced = instanced !== undefined ? instanced : false;
  29737. this._instanceDivisor = instanced ? 1 : 0;
  29738. }
  29739. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29740. /**
  29741. * Gets or sets the instance divisor when in instanced mode
  29742. */
  29743. get: function () {
  29744. return this._instanceDivisor;
  29745. },
  29746. set: function (value) {
  29747. this._instanceDivisor = value;
  29748. if (value == 0) {
  29749. this._instanced = false;
  29750. }
  29751. else {
  29752. this._instanced = true;
  29753. }
  29754. },
  29755. enumerable: true,
  29756. configurable: true
  29757. });
  29758. VertexBuffer.prototype._rebuild = function () {
  29759. if (!this._buffer) {
  29760. return;
  29761. }
  29762. this._buffer._rebuild();
  29763. };
  29764. /**
  29765. * Returns the kind of the VertexBuffer (string).
  29766. */
  29767. VertexBuffer.prototype.getKind = function () {
  29768. return this._kind;
  29769. };
  29770. // Properties
  29771. /**
  29772. * Boolean : is the VertexBuffer updatable ?
  29773. */
  29774. VertexBuffer.prototype.isUpdatable = function () {
  29775. return this._buffer.isUpdatable();
  29776. };
  29777. /**
  29778. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29779. */
  29780. VertexBuffer.prototype.getData = function () {
  29781. return this._buffer.getData();
  29782. };
  29783. /**
  29784. * Returns the WebGLBuffer associated to the VertexBuffer.
  29785. */
  29786. VertexBuffer.prototype.getBuffer = function () {
  29787. return this._buffer.getBuffer();
  29788. };
  29789. /**
  29790. * Returns the stride as a multiple of the type byte length.
  29791. * DEPRECATED. Use byteStride instead.
  29792. */
  29793. VertexBuffer.prototype.getStrideSize = function () {
  29794. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29795. };
  29796. /**
  29797. * Returns the offset as a multiple of the type byte length.
  29798. * DEPRECATED. Use byteOffset instead.
  29799. */
  29800. VertexBuffer.prototype.getOffset = function () {
  29801. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29802. };
  29803. /**
  29804. * Returns the number of components per vertex attribute (integer).
  29805. */
  29806. VertexBuffer.prototype.getSize = function () {
  29807. return this._size;
  29808. };
  29809. /**
  29810. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29811. */
  29812. VertexBuffer.prototype.getIsInstanced = function () {
  29813. return this._instanced;
  29814. };
  29815. /**
  29816. * Returns the instancing divisor, zero for non-instanced (integer).
  29817. */
  29818. VertexBuffer.prototype.getInstanceDivisor = function () {
  29819. return this._instanceDivisor;
  29820. };
  29821. // Methods
  29822. /**
  29823. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29824. * Returns the created WebGLBuffer.
  29825. */
  29826. VertexBuffer.prototype.create = function (data) {
  29827. return this._buffer.create(data);
  29828. };
  29829. /**
  29830. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29831. * This function will create a new buffer if the current one is not updatable
  29832. * Returns the updated WebGLBuffer.
  29833. */
  29834. VertexBuffer.prototype.update = function (data) {
  29835. return this._buffer.update(data);
  29836. };
  29837. /**
  29838. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29839. * Returns the directly updated WebGLBuffer.
  29840. * @param data the new data
  29841. * @param offset the new offset
  29842. * @param useBytes set to true if the offset is in bytes
  29843. */
  29844. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29845. if (useBytes === void 0) { useBytes = false; }
  29846. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29847. };
  29848. /**
  29849. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29850. */
  29851. VertexBuffer.prototype.dispose = function () {
  29852. if (this._ownsBuffer) {
  29853. this._buffer.dispose();
  29854. }
  29855. };
  29856. /**
  29857. * Enumerates each value of this vertex buffer as numbers.
  29858. * @param count the number of values to enumerate
  29859. * @param callback the callback function called for each value
  29860. */
  29861. VertexBuffer.prototype.forEach = function (count, callback) {
  29862. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29863. };
  29864. Object.defineProperty(VertexBuffer, "PositionKind", {
  29865. get: function () {
  29866. return VertexBuffer._PositionKind;
  29867. },
  29868. enumerable: true,
  29869. configurable: true
  29870. });
  29871. Object.defineProperty(VertexBuffer, "NormalKind", {
  29872. get: function () {
  29873. return VertexBuffer._NormalKind;
  29874. },
  29875. enumerable: true,
  29876. configurable: true
  29877. });
  29878. Object.defineProperty(VertexBuffer, "TangentKind", {
  29879. get: function () {
  29880. return VertexBuffer._TangentKind;
  29881. },
  29882. enumerable: true,
  29883. configurable: true
  29884. });
  29885. Object.defineProperty(VertexBuffer, "UVKind", {
  29886. get: function () {
  29887. return VertexBuffer._UVKind;
  29888. },
  29889. enumerable: true,
  29890. configurable: true
  29891. });
  29892. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29893. get: function () {
  29894. return VertexBuffer._UV2Kind;
  29895. },
  29896. enumerable: true,
  29897. configurable: true
  29898. });
  29899. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29900. get: function () {
  29901. return VertexBuffer._UV3Kind;
  29902. },
  29903. enumerable: true,
  29904. configurable: true
  29905. });
  29906. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29907. get: function () {
  29908. return VertexBuffer._UV4Kind;
  29909. },
  29910. enumerable: true,
  29911. configurable: true
  29912. });
  29913. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29914. get: function () {
  29915. return VertexBuffer._UV5Kind;
  29916. },
  29917. enumerable: true,
  29918. configurable: true
  29919. });
  29920. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29921. get: function () {
  29922. return VertexBuffer._UV6Kind;
  29923. },
  29924. enumerable: true,
  29925. configurable: true
  29926. });
  29927. Object.defineProperty(VertexBuffer, "ColorKind", {
  29928. get: function () {
  29929. return VertexBuffer._ColorKind;
  29930. },
  29931. enumerable: true,
  29932. configurable: true
  29933. });
  29934. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29935. get: function () {
  29936. return VertexBuffer._MatricesIndicesKind;
  29937. },
  29938. enumerable: true,
  29939. configurable: true
  29940. });
  29941. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29942. get: function () {
  29943. return VertexBuffer._MatricesWeightsKind;
  29944. },
  29945. enumerable: true,
  29946. configurable: true
  29947. });
  29948. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29949. get: function () {
  29950. return VertexBuffer._MatricesIndicesExtraKind;
  29951. },
  29952. enumerable: true,
  29953. configurable: true
  29954. });
  29955. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29956. get: function () {
  29957. return VertexBuffer._MatricesWeightsExtraKind;
  29958. },
  29959. enumerable: true,
  29960. configurable: true
  29961. });
  29962. /**
  29963. * Deduces the stride given a kind.
  29964. * @param kind The kind string to deduce
  29965. * @returns The deduced stride
  29966. */
  29967. VertexBuffer.DeduceStride = function (kind) {
  29968. switch (kind) {
  29969. case VertexBuffer.UVKind:
  29970. case VertexBuffer.UV2Kind:
  29971. case VertexBuffer.UV3Kind:
  29972. case VertexBuffer.UV4Kind:
  29973. case VertexBuffer.UV5Kind:
  29974. case VertexBuffer.UV6Kind:
  29975. return 2;
  29976. case VertexBuffer.NormalKind:
  29977. case VertexBuffer.PositionKind:
  29978. return 3;
  29979. case VertexBuffer.ColorKind:
  29980. case VertexBuffer.MatricesIndicesKind:
  29981. case VertexBuffer.MatricesIndicesExtraKind:
  29982. case VertexBuffer.MatricesWeightsKind:
  29983. case VertexBuffer.MatricesWeightsExtraKind:
  29984. case VertexBuffer.TangentKind:
  29985. return 4;
  29986. default:
  29987. throw new Error("Invalid kind '" + kind + "'");
  29988. }
  29989. };
  29990. /**
  29991. * Gets the byte length of the given type.
  29992. * @param type the type
  29993. * @returns the number of bytes
  29994. */
  29995. VertexBuffer.GetTypeByteLength = function (type) {
  29996. switch (type) {
  29997. case VertexBuffer.BYTE:
  29998. case VertexBuffer.UNSIGNED_BYTE:
  29999. return 1;
  30000. case VertexBuffer.SHORT:
  30001. case VertexBuffer.UNSIGNED_SHORT:
  30002. return 2;
  30003. case VertexBuffer.INT:
  30004. case VertexBuffer.FLOAT:
  30005. return 4;
  30006. default:
  30007. throw new Error("Invalid type '" + type + "'");
  30008. }
  30009. };
  30010. /**
  30011. * Enumerates each value of the given parameters as numbers.
  30012. * @param data the data to enumerate
  30013. * @param byteOffset the byte offset of the data
  30014. * @param byteStride the byte stride of the data
  30015. * @param componentCount the number of components per element
  30016. * @param componentType the type of the component
  30017. * @param count the total number of components
  30018. * @param normalized whether the data is normalized
  30019. * @param callback the callback function called for each value
  30020. */
  30021. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30022. if (data instanceof Array) {
  30023. var offset = byteOffset / 4;
  30024. var stride = byteStride / 4;
  30025. for (var index = 0; index < count; index += componentCount) {
  30026. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30027. callback(data[offset + componentIndex], index + componentIndex);
  30028. }
  30029. offset += stride;
  30030. }
  30031. }
  30032. else {
  30033. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30034. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30035. for (var index = 0; index < count; index += componentCount) {
  30036. var componentByteOffset = byteOffset;
  30037. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30038. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30039. callback(value, index + componentIndex);
  30040. componentByteOffset += componentByteLength;
  30041. }
  30042. byteOffset += byteStride;
  30043. }
  30044. }
  30045. };
  30046. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30047. switch (type) {
  30048. case VertexBuffer.BYTE: {
  30049. var value = dataView.getInt8(byteOffset);
  30050. if (normalized) {
  30051. value = Math.max(value / 127, -1);
  30052. }
  30053. return value;
  30054. }
  30055. case VertexBuffer.UNSIGNED_BYTE: {
  30056. var value = dataView.getUint8(byteOffset);
  30057. if (normalized) {
  30058. value = value / 255;
  30059. }
  30060. return value;
  30061. }
  30062. case VertexBuffer.SHORT: {
  30063. var value = dataView.getInt16(byteOffset, true);
  30064. if (normalized) {
  30065. value = Math.max(value / 16383, -1);
  30066. }
  30067. return value;
  30068. }
  30069. case VertexBuffer.UNSIGNED_SHORT: {
  30070. var value = dataView.getUint16(byteOffset, true);
  30071. if (normalized) {
  30072. value = value / 65535;
  30073. }
  30074. return value;
  30075. }
  30076. case VertexBuffer.FLOAT: {
  30077. return dataView.getFloat32(byteOffset, true);
  30078. }
  30079. default: {
  30080. throw new Error("Invalid component type " + type);
  30081. }
  30082. }
  30083. };
  30084. /**
  30085. * The byte type.
  30086. */
  30087. VertexBuffer.BYTE = 5120;
  30088. /**
  30089. * The unsigned byte type.
  30090. */
  30091. VertexBuffer.UNSIGNED_BYTE = 5121;
  30092. /**
  30093. * The short type.
  30094. */
  30095. VertexBuffer.SHORT = 5122;
  30096. /**
  30097. * The unsigned short type.
  30098. */
  30099. VertexBuffer.UNSIGNED_SHORT = 5123;
  30100. /**
  30101. * The integer type.
  30102. */
  30103. VertexBuffer.INT = 5124;
  30104. /**
  30105. * The unsigned integer type.
  30106. */
  30107. VertexBuffer.UNSIGNED_INT = 5125;
  30108. /**
  30109. * The float type.
  30110. */
  30111. VertexBuffer.FLOAT = 5126;
  30112. // Enums
  30113. VertexBuffer._PositionKind = "position";
  30114. VertexBuffer._NormalKind = "normal";
  30115. VertexBuffer._TangentKind = "tangent";
  30116. VertexBuffer._UVKind = "uv";
  30117. VertexBuffer._UV2Kind = "uv2";
  30118. VertexBuffer._UV3Kind = "uv3";
  30119. VertexBuffer._UV4Kind = "uv4";
  30120. VertexBuffer._UV5Kind = "uv5";
  30121. VertexBuffer._UV6Kind = "uv6";
  30122. VertexBuffer._ColorKind = "color";
  30123. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30124. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30125. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30126. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30127. return VertexBuffer;
  30128. }());
  30129. BABYLON.VertexBuffer = VertexBuffer;
  30130. })(BABYLON || (BABYLON = {}));
  30131. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30132. var BABYLON;
  30133. (function (BABYLON) {
  30134. /**
  30135. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30136. */
  30137. var DummyInternalTextureTracker = /** @class */ (function () {
  30138. function DummyInternalTextureTracker() {
  30139. /**
  30140. * Gets or set the previous tracker in the list
  30141. */
  30142. this.previous = null;
  30143. /**
  30144. * Gets or set the next tracker in the list
  30145. */
  30146. this.next = null;
  30147. }
  30148. return DummyInternalTextureTracker;
  30149. }());
  30150. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30151. })(BABYLON || (BABYLON = {}));
  30152. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30153. var BABYLON;
  30154. (function (BABYLON) {
  30155. /**
  30156. * Class used to store data associated with WebGL texture data for the engine
  30157. * This class should not be used directly
  30158. */
  30159. var InternalTexture = /** @class */ (function () {
  30160. /**
  30161. * Creates a new InternalTexture
  30162. * @param engine defines the engine to use
  30163. * @param dataSource defines the type of data that will be used
  30164. */
  30165. function InternalTexture(engine, dataSource) {
  30166. /**
  30167. * Observable called when the texture is loaded
  30168. */
  30169. this.onLoadedObservable = new BABYLON.Observable();
  30170. /**
  30171. * Gets or set the previous tracker in the list
  30172. */
  30173. this.previous = null;
  30174. /**
  30175. * Gets or set the next tracker in the list
  30176. */
  30177. this.next = null;
  30178. // Private
  30179. /** @hidden */
  30180. this._initialSlot = -1;
  30181. /** @hidden */
  30182. this._designatedSlot = -1;
  30183. /** @hidden */
  30184. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30185. /** @hidden */
  30186. this._comparisonFunction = 0;
  30187. /** @hidden */
  30188. this._lodGenerationScale = 0;
  30189. /** @hidden */
  30190. this._lodGenerationOffset = 0;
  30191. /** @hidden */
  30192. this._isRGBD = false;
  30193. /** @hidden */
  30194. this._references = 1;
  30195. this._engine = engine;
  30196. this._dataSource = dataSource;
  30197. this._webGLTexture = engine._createTexture();
  30198. }
  30199. /**
  30200. * Gets the Engine the texture belongs to.
  30201. * @returns The babylon engine
  30202. */
  30203. InternalTexture.prototype.getEngine = function () {
  30204. return this._engine;
  30205. };
  30206. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30207. /**
  30208. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30209. */
  30210. get: function () {
  30211. return this._dataSource;
  30212. },
  30213. enumerable: true,
  30214. configurable: true
  30215. });
  30216. /**
  30217. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30218. */
  30219. InternalTexture.prototype.incrementReferences = function () {
  30220. this._references++;
  30221. };
  30222. /**
  30223. * Change the size of the texture (not the size of the content)
  30224. * @param width defines the new width
  30225. * @param height defines the new height
  30226. * @param depth defines the new depth (1 by default)
  30227. */
  30228. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30229. if (depth === void 0) { depth = 1; }
  30230. this.width = width;
  30231. this.height = height;
  30232. this.depth = depth;
  30233. this.baseWidth = width;
  30234. this.baseHeight = height;
  30235. this.baseDepth = depth;
  30236. this._size = width * height * depth;
  30237. };
  30238. /** @hidden */
  30239. InternalTexture.prototype._rebuild = function () {
  30240. var _this = this;
  30241. var proxy;
  30242. this.isReady = false;
  30243. this._cachedCoordinatesMode = null;
  30244. this._cachedWrapU = null;
  30245. this._cachedWrapV = null;
  30246. this._cachedAnisotropicFilteringLevel = null;
  30247. switch (this._dataSource) {
  30248. case InternalTexture.DATASOURCE_TEMP:
  30249. return;
  30250. case InternalTexture.DATASOURCE_URL:
  30251. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30252. _this.isReady = true;
  30253. }, null, this._buffer, undefined, this.format);
  30254. proxy._swapAndDie(this);
  30255. return;
  30256. case InternalTexture.DATASOURCE_RAW:
  30257. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30258. proxy._swapAndDie(this);
  30259. this.isReady = true;
  30260. return;
  30261. case InternalTexture.DATASOURCE_RAW3D:
  30262. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30263. proxy._swapAndDie(this);
  30264. this.isReady = true;
  30265. return;
  30266. case InternalTexture.DATASOURCE_DYNAMIC:
  30267. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30268. proxy._swapAndDie(this);
  30269. // The engine will make sure to update content so no need to flag it as isReady = true
  30270. return;
  30271. case InternalTexture.DATASOURCE_RENDERTARGET:
  30272. var options = new BABYLON.RenderTargetCreationOptions();
  30273. options.generateDepthBuffer = this._generateDepthBuffer;
  30274. options.generateMipMaps = this.generateMipMaps;
  30275. options.generateStencilBuffer = this._generateStencilBuffer;
  30276. options.samplingMode = this.samplingMode;
  30277. options.type = this.type;
  30278. if (this.isCube) {
  30279. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30280. }
  30281. else {
  30282. var size = {
  30283. width: this.width,
  30284. height: this.height
  30285. };
  30286. proxy = this._engine.createRenderTargetTexture(size, options);
  30287. }
  30288. proxy._swapAndDie(this);
  30289. this.isReady = true;
  30290. return;
  30291. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30292. var depthTextureOptions = {
  30293. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30294. comparisonFunction: this._comparisonFunction,
  30295. generateStencil: this._generateStencilBuffer,
  30296. isCube: this.isCube
  30297. };
  30298. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30299. proxy._swapAndDie(this);
  30300. this.isReady = true;
  30301. return;
  30302. case InternalTexture.DATASOURCE_CUBE:
  30303. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30304. _this.isReady = true;
  30305. }, null, this.format, this._extension);
  30306. proxy._swapAndDie(this);
  30307. return;
  30308. case InternalTexture.DATASOURCE_CUBERAW:
  30309. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30310. proxy._swapAndDie(this);
  30311. this.isReady = true;
  30312. return;
  30313. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30314. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30315. if (proxy) {
  30316. proxy._swapAndDie(_this);
  30317. }
  30318. _this.isReady = true;
  30319. }, null, this.format, this._extension);
  30320. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30321. return;
  30322. }
  30323. };
  30324. InternalTexture.prototype._swapAndDie = function (target) {
  30325. target._webGLTexture = this._webGLTexture;
  30326. if (this._framebuffer) {
  30327. target._framebuffer = this._framebuffer;
  30328. }
  30329. if (this._depthStencilBuffer) {
  30330. target._depthStencilBuffer = this._depthStencilBuffer;
  30331. }
  30332. if (this._lodTextureHigh) {
  30333. if (target._lodTextureHigh) {
  30334. target._lodTextureHigh.dispose();
  30335. }
  30336. target._lodTextureHigh = this._lodTextureHigh;
  30337. }
  30338. if (this._lodTextureMid) {
  30339. if (target._lodTextureMid) {
  30340. target._lodTextureMid.dispose();
  30341. }
  30342. target._lodTextureMid = this._lodTextureMid;
  30343. }
  30344. if (this._lodTextureLow) {
  30345. if (target._lodTextureLow) {
  30346. target._lodTextureLow.dispose();
  30347. }
  30348. target._lodTextureLow = this._lodTextureLow;
  30349. }
  30350. var cache = this._engine.getLoadedTexturesCache();
  30351. var index = cache.indexOf(this);
  30352. if (index !== -1) {
  30353. cache.splice(index, 1);
  30354. }
  30355. };
  30356. /**
  30357. * Dispose the current allocated resources
  30358. */
  30359. InternalTexture.prototype.dispose = function () {
  30360. if (!this._webGLTexture) {
  30361. return;
  30362. }
  30363. this._references--;
  30364. if (this._references === 0) {
  30365. this._engine._releaseTexture(this);
  30366. this._webGLTexture = null;
  30367. this.previous = null;
  30368. this.next = null;
  30369. }
  30370. };
  30371. /**
  30372. * The source of the texture data is unknown
  30373. */
  30374. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30375. /**
  30376. * Texture data comes from an URL
  30377. */
  30378. InternalTexture.DATASOURCE_URL = 1;
  30379. /**
  30380. * Texture data is only used for temporary storage
  30381. */
  30382. InternalTexture.DATASOURCE_TEMP = 2;
  30383. /**
  30384. * Texture data comes from raw data (ArrayBuffer)
  30385. */
  30386. InternalTexture.DATASOURCE_RAW = 3;
  30387. /**
  30388. * Texture content is dynamic (video or dynamic texture)
  30389. */
  30390. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30391. /**
  30392. * Texture content is generated by rendering to it
  30393. */
  30394. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30395. /**
  30396. * Texture content is part of a multi render target process
  30397. */
  30398. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30399. /**
  30400. * Texture data comes from a cube data file
  30401. */
  30402. InternalTexture.DATASOURCE_CUBE = 7;
  30403. /**
  30404. * Texture data comes from a raw cube data
  30405. */
  30406. InternalTexture.DATASOURCE_CUBERAW = 8;
  30407. /**
  30408. * Texture data come from a prefiltered cube data file
  30409. */
  30410. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30411. /**
  30412. * Texture content is raw 3D data
  30413. */
  30414. InternalTexture.DATASOURCE_RAW3D = 10;
  30415. /**
  30416. * Texture content is a depth texture
  30417. */
  30418. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30419. return InternalTexture;
  30420. }());
  30421. BABYLON.InternalTexture = InternalTexture;
  30422. })(BABYLON || (BABYLON = {}));
  30423. //# sourceMappingURL=babylon.internalTexture.js.map
  30424. var BABYLON;
  30425. (function (BABYLON) {
  30426. var BaseTexture = /** @class */ (function () {
  30427. function BaseTexture(scene) {
  30428. this._hasAlpha = false;
  30429. this.getAlphaFromRGB = false;
  30430. this.level = 1;
  30431. this.coordinatesIndex = 0;
  30432. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30433. /**
  30434. * | Value | Type | Description |
  30435. * | ----- | ------------------ | ----------- |
  30436. * | 0 | CLAMP_ADDRESSMODE | |
  30437. * | 1 | WRAP_ADDRESSMODE | |
  30438. * | 2 | MIRROR_ADDRESSMODE | |
  30439. */
  30440. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30441. /**
  30442. * | Value | Type | Description |
  30443. * | ----- | ------------------ | ----------- |
  30444. * | 0 | CLAMP_ADDRESSMODE | |
  30445. * | 1 | WRAP_ADDRESSMODE | |
  30446. * | 2 | MIRROR_ADDRESSMODE | |
  30447. */
  30448. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30449. /**
  30450. * | Value | Type | Description |
  30451. * | ----- | ------------------ | ----------- |
  30452. * | 0 | CLAMP_ADDRESSMODE | |
  30453. * | 1 | WRAP_ADDRESSMODE | |
  30454. * | 2 | MIRROR_ADDRESSMODE | |
  30455. */
  30456. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30457. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30458. this.isCube = false;
  30459. this.is3D = false;
  30460. this.gammaSpace = true;
  30461. this.invertZ = false;
  30462. this.lodLevelInAlpha = false;
  30463. this.isRenderTarget = false;
  30464. this.animations = new Array();
  30465. /**
  30466. * An event triggered when the texture is disposed.
  30467. */
  30468. this.onDisposeObservable = new BABYLON.Observable();
  30469. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30470. this._cachedSize = BABYLON.Size.Zero();
  30471. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30472. if (this._scene) {
  30473. this._scene.textures.push(this);
  30474. }
  30475. this._uid = null;
  30476. }
  30477. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30478. get: function () {
  30479. return this._hasAlpha;
  30480. },
  30481. set: function (value) {
  30482. if (this._hasAlpha === value) {
  30483. return;
  30484. }
  30485. this._hasAlpha = value;
  30486. if (this._scene) {
  30487. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30488. }
  30489. },
  30490. enumerable: true,
  30491. configurable: true
  30492. });
  30493. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30494. get: function () {
  30495. return this._coordinatesMode;
  30496. },
  30497. /**
  30498. * How a texture is mapped.
  30499. *
  30500. * | Value | Type | Description |
  30501. * | ----- | ----------------------------------- | ----------- |
  30502. * | 0 | EXPLICIT_MODE | |
  30503. * | 1 | SPHERICAL_MODE | |
  30504. * | 2 | PLANAR_MODE | |
  30505. * | 3 | CUBIC_MODE | |
  30506. * | 4 | PROJECTION_MODE | |
  30507. * | 5 | SKYBOX_MODE | |
  30508. * | 6 | INVCUBIC_MODE | |
  30509. * | 7 | EQUIRECTANGULAR_MODE | |
  30510. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30511. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30512. */
  30513. set: function (value) {
  30514. if (this._coordinatesMode === value) {
  30515. return;
  30516. }
  30517. this._coordinatesMode = value;
  30518. if (this._scene) {
  30519. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30520. }
  30521. },
  30522. enumerable: true,
  30523. configurable: true
  30524. });
  30525. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30526. /**
  30527. * Gets whether or not the texture contains RGBD data.
  30528. */
  30529. get: function () {
  30530. return this._texture != null && this._texture._isRGBD;
  30531. },
  30532. enumerable: true,
  30533. configurable: true
  30534. });
  30535. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30536. get: function () {
  30537. if (this._texture)
  30538. return this._texture._lodGenerationOffset;
  30539. return 0.0;
  30540. },
  30541. set: function (value) {
  30542. if (this._texture)
  30543. this._texture._lodGenerationOffset = value;
  30544. },
  30545. enumerable: true,
  30546. configurable: true
  30547. });
  30548. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30549. get: function () {
  30550. if (this._texture)
  30551. return this._texture._lodGenerationScale;
  30552. return 0.0;
  30553. },
  30554. set: function (value) {
  30555. if (this._texture)
  30556. this._texture._lodGenerationScale = value;
  30557. },
  30558. enumerable: true,
  30559. configurable: true
  30560. });
  30561. Object.defineProperty(BaseTexture.prototype, "uid", {
  30562. get: function () {
  30563. if (!this._uid) {
  30564. this._uid = BABYLON.Tools.RandomId();
  30565. }
  30566. return this._uid;
  30567. },
  30568. enumerable: true,
  30569. configurable: true
  30570. });
  30571. BaseTexture.prototype.toString = function () {
  30572. return this.name;
  30573. };
  30574. BaseTexture.prototype.getClassName = function () {
  30575. return "BaseTexture";
  30576. };
  30577. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30578. set: function (callback) {
  30579. if (this._onDisposeObserver) {
  30580. this.onDisposeObservable.remove(this._onDisposeObserver);
  30581. }
  30582. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30583. },
  30584. enumerable: true,
  30585. configurable: true
  30586. });
  30587. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30588. get: function () {
  30589. return true;
  30590. },
  30591. enumerable: true,
  30592. configurable: true
  30593. });
  30594. BaseTexture.prototype.getScene = function () {
  30595. return this._scene;
  30596. };
  30597. BaseTexture.prototype.getTextureMatrix = function () {
  30598. return BABYLON.Matrix.IdentityReadOnly;
  30599. };
  30600. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30601. return BABYLON.Matrix.IdentityReadOnly;
  30602. };
  30603. BaseTexture.prototype.getInternalTexture = function () {
  30604. return this._texture;
  30605. };
  30606. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30607. return !this.isBlocking || this.isReady();
  30608. };
  30609. BaseTexture.prototype.isReady = function () {
  30610. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30611. this.delayLoad();
  30612. return false;
  30613. }
  30614. if (this._texture) {
  30615. return this._texture.isReady;
  30616. }
  30617. return false;
  30618. };
  30619. BaseTexture.prototype.getSize = function () {
  30620. if (this._texture) {
  30621. if (this._texture.width) {
  30622. this._cachedSize.width = this._texture.width;
  30623. this._cachedSize.height = this._texture.height;
  30624. return this._cachedSize;
  30625. }
  30626. if (this._texture._size) {
  30627. this._cachedSize.width = this._texture._size;
  30628. this._cachedSize.height = this._texture._size;
  30629. return this._cachedSize;
  30630. }
  30631. }
  30632. return this._cachedSize;
  30633. };
  30634. BaseTexture.prototype.getBaseSize = function () {
  30635. if (!this.isReady() || !this._texture)
  30636. return BABYLON.Size.Zero();
  30637. if (this._texture._size) {
  30638. return new BABYLON.Size(this._texture._size, this._texture._size);
  30639. }
  30640. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30641. };
  30642. BaseTexture.prototype.scale = function (ratio) {
  30643. };
  30644. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30645. get: function () {
  30646. return false;
  30647. },
  30648. enumerable: true,
  30649. configurable: true
  30650. });
  30651. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30652. if (!this._scene) {
  30653. return null;
  30654. }
  30655. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30656. for (var index = 0; index < texturesCache.length; index++) {
  30657. var texturesCacheEntry = texturesCache[index];
  30658. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30659. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30660. texturesCacheEntry.incrementReferences();
  30661. return texturesCacheEntry;
  30662. }
  30663. }
  30664. }
  30665. return null;
  30666. };
  30667. BaseTexture.prototype._rebuild = function () {
  30668. };
  30669. BaseTexture.prototype.delayLoad = function () {
  30670. };
  30671. BaseTexture.prototype.clone = function () {
  30672. return null;
  30673. };
  30674. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30675. get: function () {
  30676. if (!this._texture) {
  30677. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30678. }
  30679. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30680. },
  30681. enumerable: true,
  30682. configurable: true
  30683. });
  30684. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30685. get: function () {
  30686. if (!this._texture) {
  30687. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30688. }
  30689. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30690. },
  30691. enumerable: true,
  30692. configurable: true
  30693. });
  30694. /**
  30695. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30696. * This will returns an RGBA array buffer containing either in values (0-255) or
  30697. * float values (0-1) depending of the underlying buffer type.
  30698. * @param faceIndex The face of the texture to read (in case of cube texture)
  30699. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30700. * @returns The Array buffer containing the pixels data.
  30701. */
  30702. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30703. if (faceIndex === void 0) { faceIndex = 0; }
  30704. if (level === void 0) { level = 0; }
  30705. if (!this._texture) {
  30706. return null;
  30707. }
  30708. var size = this.getSize();
  30709. var width = size.width;
  30710. var height = size.height;
  30711. var scene = this.getScene();
  30712. if (!scene) {
  30713. return null;
  30714. }
  30715. var engine = scene.getEngine();
  30716. if (level != 0) {
  30717. width = width / Math.pow(2, level);
  30718. height = height / Math.pow(2, level);
  30719. width = Math.round(width);
  30720. height = Math.round(height);
  30721. }
  30722. if (this._texture.isCube) {
  30723. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30724. }
  30725. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30726. };
  30727. BaseTexture.prototype.releaseInternalTexture = function () {
  30728. if (this._texture) {
  30729. this._texture.dispose();
  30730. this._texture = null;
  30731. }
  30732. };
  30733. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30734. get: function () {
  30735. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30736. return null;
  30737. }
  30738. if (!this._texture._sphericalPolynomial) {
  30739. this._texture._sphericalPolynomial =
  30740. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30741. }
  30742. return this._texture._sphericalPolynomial;
  30743. },
  30744. set: function (value) {
  30745. if (this._texture) {
  30746. this._texture._sphericalPolynomial = value;
  30747. }
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30753. get: function () {
  30754. if (this._texture) {
  30755. return this._texture._lodTextureHigh;
  30756. }
  30757. return null;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30763. get: function () {
  30764. if (this._texture) {
  30765. return this._texture._lodTextureMid;
  30766. }
  30767. return null;
  30768. },
  30769. enumerable: true,
  30770. configurable: true
  30771. });
  30772. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30773. get: function () {
  30774. if (this._texture) {
  30775. return this._texture._lodTextureLow;
  30776. }
  30777. return null;
  30778. },
  30779. enumerable: true,
  30780. configurable: true
  30781. });
  30782. BaseTexture.prototype.dispose = function () {
  30783. if (!this._scene) {
  30784. return;
  30785. }
  30786. // Animations
  30787. this._scene.stopAnimation(this);
  30788. // Remove from scene
  30789. this._scene._removePendingData(this);
  30790. var index = this._scene.textures.indexOf(this);
  30791. if (index >= 0) {
  30792. this._scene.textures.splice(index, 1);
  30793. }
  30794. if (this._texture === undefined) {
  30795. return;
  30796. }
  30797. // Release
  30798. this.releaseInternalTexture();
  30799. // Callback
  30800. this.onDisposeObservable.notifyObservers(this);
  30801. this.onDisposeObservable.clear();
  30802. };
  30803. BaseTexture.prototype.serialize = function () {
  30804. if (!this.name) {
  30805. return null;
  30806. }
  30807. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30808. // Animations
  30809. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30810. return serializationObject;
  30811. };
  30812. BaseTexture.WhenAllReady = function (textures, callback) {
  30813. var numRemaining = textures.length;
  30814. if (numRemaining === 0) {
  30815. callback();
  30816. return;
  30817. }
  30818. var _loop_1 = function () {
  30819. texture = textures[i];
  30820. if (texture.isReady()) {
  30821. if (--numRemaining === 0) {
  30822. callback();
  30823. }
  30824. }
  30825. else {
  30826. onLoadObservable = texture.onLoadObservable;
  30827. var onLoadCallback_1 = function () {
  30828. onLoadObservable.removeCallback(onLoadCallback_1);
  30829. if (--numRemaining === 0) {
  30830. callback();
  30831. }
  30832. };
  30833. onLoadObservable.add(onLoadCallback_1);
  30834. }
  30835. };
  30836. var texture, onLoadObservable;
  30837. for (var i = 0; i < textures.length; i++) {
  30838. _loop_1();
  30839. }
  30840. };
  30841. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30842. __decorate([
  30843. BABYLON.serialize()
  30844. ], BaseTexture.prototype, "name", void 0);
  30845. __decorate([
  30846. BABYLON.serialize("hasAlpha")
  30847. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30848. __decorate([
  30849. BABYLON.serialize()
  30850. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30851. __decorate([
  30852. BABYLON.serialize()
  30853. ], BaseTexture.prototype, "level", void 0);
  30854. __decorate([
  30855. BABYLON.serialize()
  30856. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30857. __decorate([
  30858. BABYLON.serialize("coordinatesMode")
  30859. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30860. __decorate([
  30861. BABYLON.serialize()
  30862. ], BaseTexture.prototype, "wrapU", void 0);
  30863. __decorate([
  30864. BABYLON.serialize()
  30865. ], BaseTexture.prototype, "wrapV", void 0);
  30866. __decorate([
  30867. BABYLON.serialize()
  30868. ], BaseTexture.prototype, "wrapR", void 0);
  30869. __decorate([
  30870. BABYLON.serialize()
  30871. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30872. __decorate([
  30873. BABYLON.serialize()
  30874. ], BaseTexture.prototype, "isCube", void 0);
  30875. __decorate([
  30876. BABYLON.serialize()
  30877. ], BaseTexture.prototype, "is3D", void 0);
  30878. __decorate([
  30879. BABYLON.serialize()
  30880. ], BaseTexture.prototype, "gammaSpace", void 0);
  30881. __decorate([
  30882. BABYLON.serialize()
  30883. ], BaseTexture.prototype, "invertZ", void 0);
  30884. __decorate([
  30885. BABYLON.serialize()
  30886. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30887. __decorate([
  30888. BABYLON.serialize()
  30889. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30890. __decorate([
  30891. BABYLON.serialize()
  30892. ], BaseTexture.prototype, "lodGenerationScale", null);
  30893. __decorate([
  30894. BABYLON.serialize()
  30895. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30896. return BaseTexture;
  30897. }());
  30898. BABYLON.BaseTexture = BaseTexture;
  30899. })(BABYLON || (BABYLON = {}));
  30900. //# sourceMappingURL=babylon.baseTexture.js.map
  30901. var BABYLON;
  30902. (function (BABYLON) {
  30903. var Texture = /** @class */ (function (_super) {
  30904. __extends(Texture, _super);
  30905. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30906. if (noMipmap === void 0) { noMipmap = false; }
  30907. if (invertY === void 0) { invertY = true; }
  30908. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30909. if (onLoad === void 0) { onLoad = null; }
  30910. if (onError === void 0) { onError = null; }
  30911. if (buffer === void 0) { buffer = null; }
  30912. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30913. var _this = _super.call(this, scene) || this;
  30914. _this.uOffset = 0;
  30915. _this.vOffset = 0;
  30916. _this.uScale = 1.0;
  30917. _this.vScale = 1.0;
  30918. _this.uAng = 0;
  30919. _this.vAng = 0;
  30920. _this.wAng = 0;
  30921. /**
  30922. * Defines the center of rotation (U)
  30923. */
  30924. _this.uRotationCenter = 0.5;
  30925. /**
  30926. * Defines the center of rotation (V)
  30927. */
  30928. _this.vRotationCenter = 0.5;
  30929. /**
  30930. * Defines the center of rotation (W)
  30931. */
  30932. _this.wRotationCenter = 0.5;
  30933. _this._isBlocking = true;
  30934. _this.name = url || "";
  30935. _this.url = url;
  30936. _this._noMipmap = noMipmap;
  30937. _this._invertY = invertY;
  30938. _this._samplingMode = samplingMode;
  30939. _this._buffer = buffer;
  30940. _this._deleteBuffer = deleteBuffer;
  30941. if (format) {
  30942. _this._format = format;
  30943. }
  30944. scene = _this.getScene();
  30945. if (!scene) {
  30946. return _this;
  30947. }
  30948. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30949. var load = function () {
  30950. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30951. _this.onLoadObservable.notifyObservers(_this);
  30952. }
  30953. if (onLoad) {
  30954. onLoad();
  30955. }
  30956. if (!_this.isBlocking && scene) {
  30957. scene.resetCachedMaterial();
  30958. }
  30959. };
  30960. if (!_this.url) {
  30961. _this._delayedOnLoad = load;
  30962. _this._delayedOnError = onError;
  30963. return _this;
  30964. }
  30965. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30966. if (!_this._texture) {
  30967. if (!scene.useDelayedTextureLoading) {
  30968. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30969. if (deleteBuffer) {
  30970. delete _this._buffer;
  30971. }
  30972. }
  30973. else {
  30974. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30975. _this._delayedOnLoad = load;
  30976. _this._delayedOnError = onError;
  30977. }
  30978. }
  30979. else {
  30980. if (_this._texture.isReady) {
  30981. BABYLON.Tools.SetImmediate(function () { return load(); });
  30982. }
  30983. else {
  30984. _this._texture.onLoadedObservable.add(load);
  30985. }
  30986. }
  30987. return _this;
  30988. }
  30989. Object.defineProperty(Texture.prototype, "noMipmap", {
  30990. get: function () {
  30991. return this._noMipmap;
  30992. },
  30993. enumerable: true,
  30994. configurable: true
  30995. });
  30996. Object.defineProperty(Texture.prototype, "isBlocking", {
  30997. get: function () {
  30998. return this._isBlocking;
  30999. },
  31000. set: function (value) {
  31001. this._isBlocking = value;
  31002. },
  31003. enumerable: true,
  31004. configurable: true
  31005. });
  31006. Object.defineProperty(Texture.prototype, "samplingMode", {
  31007. get: function () {
  31008. return this._samplingMode;
  31009. },
  31010. enumerable: true,
  31011. configurable: true
  31012. });
  31013. /**
  31014. * Update the url (and optional buffer) of this texture if url was null during construction.
  31015. * @param url the url of the texture
  31016. * @param buffer the buffer of the texture (defaults to null)
  31017. */
  31018. Texture.prototype.updateURL = function (url, buffer) {
  31019. if (buffer === void 0) { buffer = null; }
  31020. if (this.url) {
  31021. throw new Error("URL is already set");
  31022. }
  31023. this.url = url;
  31024. this._buffer = buffer;
  31025. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31026. this.delayLoad();
  31027. };
  31028. Texture.prototype.delayLoad = function () {
  31029. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31030. return;
  31031. }
  31032. var scene = this.getScene();
  31033. if (!scene) {
  31034. return;
  31035. }
  31036. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31037. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31038. if (!this._texture) {
  31039. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31040. if (this._deleteBuffer) {
  31041. delete this._buffer;
  31042. }
  31043. }
  31044. else {
  31045. if (this._delayedOnLoad) {
  31046. if (this._texture.isReady) {
  31047. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31048. }
  31049. else {
  31050. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31051. }
  31052. }
  31053. }
  31054. this._delayedOnLoad = null;
  31055. this._delayedOnError = null;
  31056. };
  31057. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31058. if (!this._texture) {
  31059. return;
  31060. }
  31061. var scene = this.getScene();
  31062. if (!scene) {
  31063. return;
  31064. }
  31065. this._samplingMode = samplingMode;
  31066. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31067. };
  31068. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31069. x *= this.uScale;
  31070. y *= this.vScale;
  31071. x -= this.uRotationCenter * this.uScale;
  31072. y -= this.vRotationCenter * this.vScale;
  31073. z -= this.wRotationCenter;
  31074. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31075. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31076. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31077. t.z += this.wRotationCenter;
  31078. };
  31079. Texture.prototype.getTextureMatrix = function () {
  31080. var _this = this;
  31081. if (this.uOffset === this._cachedUOffset &&
  31082. this.vOffset === this._cachedVOffset &&
  31083. this.uScale === this._cachedUScale &&
  31084. this.vScale === this._cachedVScale &&
  31085. this.uAng === this._cachedUAng &&
  31086. this.vAng === this._cachedVAng &&
  31087. this.wAng === this._cachedWAng) {
  31088. return this._cachedTextureMatrix;
  31089. }
  31090. this._cachedUOffset = this.uOffset;
  31091. this._cachedVOffset = this.vOffset;
  31092. this._cachedUScale = this.uScale;
  31093. this._cachedVScale = this.vScale;
  31094. this._cachedUAng = this.uAng;
  31095. this._cachedVAng = this.vAng;
  31096. this._cachedWAng = this.wAng;
  31097. if (!this._cachedTextureMatrix) {
  31098. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31099. this._rowGenerationMatrix = new BABYLON.Matrix();
  31100. this._t0 = BABYLON.Vector3.Zero();
  31101. this._t1 = BABYLON.Vector3.Zero();
  31102. this._t2 = BABYLON.Vector3.Zero();
  31103. }
  31104. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31105. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31106. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31107. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31108. this._t1.subtractInPlace(this._t0);
  31109. this._t2.subtractInPlace(this._t0);
  31110. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31111. this._cachedTextureMatrix.m[0] = this._t1.x;
  31112. this._cachedTextureMatrix.m[1] = this._t1.y;
  31113. this._cachedTextureMatrix.m[2] = this._t1.z;
  31114. this._cachedTextureMatrix.m[4] = this._t2.x;
  31115. this._cachedTextureMatrix.m[5] = this._t2.y;
  31116. this._cachedTextureMatrix.m[6] = this._t2.z;
  31117. this._cachedTextureMatrix.m[8] = this._t0.x;
  31118. this._cachedTextureMatrix.m[9] = this._t0.y;
  31119. this._cachedTextureMatrix.m[10] = this._t0.z;
  31120. var scene = this.getScene();
  31121. if (!scene) {
  31122. return this._cachedTextureMatrix;
  31123. }
  31124. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31125. return mat.hasTexture(_this);
  31126. });
  31127. return this._cachedTextureMatrix;
  31128. };
  31129. Texture.prototype.getReflectionTextureMatrix = function () {
  31130. var _this = this;
  31131. var scene = this.getScene();
  31132. if (!scene) {
  31133. return this._cachedTextureMatrix;
  31134. }
  31135. if (this.uOffset === this._cachedUOffset &&
  31136. this.vOffset === this._cachedVOffset &&
  31137. this.uScale === this._cachedUScale &&
  31138. this.vScale === this._cachedVScale &&
  31139. this.coordinatesMode === this._cachedCoordinatesMode) {
  31140. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31141. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31142. return this._cachedTextureMatrix;
  31143. }
  31144. }
  31145. else {
  31146. return this._cachedTextureMatrix;
  31147. }
  31148. }
  31149. if (!this._cachedTextureMatrix) {
  31150. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31151. }
  31152. if (!this._projectionModeMatrix) {
  31153. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31154. }
  31155. this._cachedUOffset = this.uOffset;
  31156. this._cachedVOffset = this.vOffset;
  31157. this._cachedUScale = this.uScale;
  31158. this._cachedVScale = this.vScale;
  31159. this._cachedCoordinatesMode = this.coordinatesMode;
  31160. switch (this.coordinatesMode) {
  31161. case Texture.PLANAR_MODE:
  31162. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31163. this._cachedTextureMatrix[0] = this.uScale;
  31164. this._cachedTextureMatrix[5] = this.vScale;
  31165. this._cachedTextureMatrix[12] = this.uOffset;
  31166. this._cachedTextureMatrix[13] = this.vOffset;
  31167. break;
  31168. case Texture.PROJECTION_MODE:
  31169. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31170. this._projectionModeMatrix.m[0] = 0.5;
  31171. this._projectionModeMatrix.m[5] = -0.5;
  31172. this._projectionModeMatrix.m[10] = 0.0;
  31173. this._projectionModeMatrix.m[12] = 0.5;
  31174. this._projectionModeMatrix.m[13] = 0.5;
  31175. this._projectionModeMatrix.m[14] = 1.0;
  31176. this._projectionModeMatrix.m[15] = 1.0;
  31177. var projectionMatrix = scene.getProjectionMatrix();
  31178. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31179. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31180. break;
  31181. default:
  31182. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31183. break;
  31184. }
  31185. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31186. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31187. });
  31188. return this._cachedTextureMatrix;
  31189. };
  31190. Texture.prototype.clone = function () {
  31191. var _this = this;
  31192. return BABYLON.SerializationHelper.Clone(function () {
  31193. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31194. }, this);
  31195. };
  31196. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31197. get: function () {
  31198. if (!this._onLoadObservable) {
  31199. this._onLoadObservable = new BABYLON.Observable();
  31200. }
  31201. return this._onLoadObservable;
  31202. },
  31203. enumerable: true,
  31204. configurable: true
  31205. });
  31206. Texture.prototype.serialize = function () {
  31207. var serializationObject = _super.prototype.serialize.call(this);
  31208. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31209. serializationObject.base64String = this._buffer;
  31210. serializationObject.name = serializationObject.name.replace("data:", "");
  31211. }
  31212. serializationObject.invertY = this._invertY;
  31213. serializationObject.samplingMode = this.samplingMode;
  31214. return serializationObject;
  31215. };
  31216. Texture.prototype.getClassName = function () {
  31217. return "Texture";
  31218. };
  31219. Texture.prototype.dispose = function () {
  31220. _super.prototype.dispose.call(this);
  31221. if (this._onLoadObservable) {
  31222. this._onLoadObservable.clear();
  31223. this._onLoadObservable = null;
  31224. }
  31225. this._delayedOnLoad = null;
  31226. this._delayedOnError = null;
  31227. };
  31228. // Statics
  31229. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31230. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31231. if (onLoad === void 0) { onLoad = null; }
  31232. if (onError === void 0) { onError = null; }
  31233. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31234. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31235. };
  31236. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31237. if (parsedTexture.customType) {
  31238. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31239. // Update Sampling Mode
  31240. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31241. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31242. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31243. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31244. }
  31245. }
  31246. return parsedCustomTexture;
  31247. }
  31248. if (parsedTexture.isCube) {
  31249. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31250. }
  31251. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31252. return null;
  31253. }
  31254. var texture = BABYLON.SerializationHelper.Parse(function () {
  31255. var generateMipMaps = true;
  31256. if (parsedTexture.noMipmap) {
  31257. generateMipMaps = false;
  31258. }
  31259. if (parsedTexture.mirrorPlane) {
  31260. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31261. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31262. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31263. return mirrorTexture;
  31264. }
  31265. else if (parsedTexture.isRenderTarget) {
  31266. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31267. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31268. return renderTargetTexture;
  31269. }
  31270. else {
  31271. var texture;
  31272. if (parsedTexture.base64String) {
  31273. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31274. }
  31275. else {
  31276. var url = rootUrl + parsedTexture.name;
  31277. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31278. url = parsedTexture.url;
  31279. }
  31280. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31281. }
  31282. return texture;
  31283. }
  31284. }, parsedTexture, scene);
  31285. // Update Sampling Mode
  31286. if (parsedTexture.samplingMode) {
  31287. var sampling = parsedTexture.samplingMode;
  31288. if (texture._samplingMode !== sampling) {
  31289. texture.updateSamplingMode(sampling);
  31290. }
  31291. }
  31292. // Animations
  31293. if (parsedTexture.animations) {
  31294. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31295. var parsedAnimation = parsedTexture.animations[animationIndex];
  31296. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31297. }
  31298. }
  31299. return texture;
  31300. };
  31301. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31302. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31303. if (noMipmap === void 0) { noMipmap = false; }
  31304. if (invertY === void 0) { invertY = true; }
  31305. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31306. if (onLoad === void 0) { onLoad = null; }
  31307. if (onError === void 0) { onError = null; }
  31308. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31309. if (name.substr(0, 5) !== "data:") {
  31310. name = "data:" + name;
  31311. }
  31312. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31313. };
  31314. // Constants
  31315. Texture.NEAREST_SAMPLINGMODE = 1;
  31316. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31317. Texture.BILINEAR_SAMPLINGMODE = 2;
  31318. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31319. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31320. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31321. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31322. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31323. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31324. Texture.NEAREST_LINEAR = 7;
  31325. Texture.NEAREST_NEAREST = 8;
  31326. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31327. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31328. Texture.LINEAR_LINEAR = 11;
  31329. Texture.LINEAR_NEAREST = 12;
  31330. Texture.EXPLICIT_MODE = 0;
  31331. Texture.SPHERICAL_MODE = 1;
  31332. Texture.PLANAR_MODE = 2;
  31333. Texture.CUBIC_MODE = 3;
  31334. Texture.PROJECTION_MODE = 4;
  31335. Texture.SKYBOX_MODE = 5;
  31336. Texture.INVCUBIC_MODE = 6;
  31337. Texture.EQUIRECTANGULAR_MODE = 7;
  31338. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31339. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31340. Texture.CLAMP_ADDRESSMODE = 0;
  31341. Texture.WRAP_ADDRESSMODE = 1;
  31342. Texture.MIRROR_ADDRESSMODE = 2;
  31343. /**
  31344. * 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
  31345. */
  31346. Texture.UseSerializedUrlIfAny = false;
  31347. __decorate([
  31348. BABYLON.serialize()
  31349. ], Texture.prototype, "url", void 0);
  31350. __decorate([
  31351. BABYLON.serialize()
  31352. ], Texture.prototype, "uOffset", void 0);
  31353. __decorate([
  31354. BABYLON.serialize()
  31355. ], Texture.prototype, "vOffset", void 0);
  31356. __decorate([
  31357. BABYLON.serialize()
  31358. ], Texture.prototype, "uScale", void 0);
  31359. __decorate([
  31360. BABYLON.serialize()
  31361. ], Texture.prototype, "vScale", void 0);
  31362. __decorate([
  31363. BABYLON.serialize()
  31364. ], Texture.prototype, "uAng", void 0);
  31365. __decorate([
  31366. BABYLON.serialize()
  31367. ], Texture.prototype, "vAng", void 0);
  31368. __decorate([
  31369. BABYLON.serialize()
  31370. ], Texture.prototype, "wAng", void 0);
  31371. __decorate([
  31372. BABYLON.serialize()
  31373. ], Texture.prototype, "uRotationCenter", void 0);
  31374. __decorate([
  31375. BABYLON.serialize()
  31376. ], Texture.prototype, "vRotationCenter", void 0);
  31377. __decorate([
  31378. BABYLON.serialize()
  31379. ], Texture.prototype, "wRotationCenter", void 0);
  31380. __decorate([
  31381. BABYLON.serialize()
  31382. ], Texture.prototype, "isBlocking", null);
  31383. return Texture;
  31384. }(BABYLON.BaseTexture));
  31385. BABYLON.Texture = Texture;
  31386. })(BABYLON || (BABYLON = {}));
  31387. //# sourceMappingURL=babylon.texture.js.map
  31388. var BABYLON;
  31389. (function (BABYLON) {
  31390. /**
  31391. * @hidden
  31392. **/
  31393. var _InstancesBatch = /** @class */ (function () {
  31394. function _InstancesBatch() {
  31395. this.mustReturn = false;
  31396. this.visibleInstances = new Array();
  31397. this.renderSelf = new Array();
  31398. }
  31399. return _InstancesBatch;
  31400. }());
  31401. BABYLON._InstancesBatch = _InstancesBatch;
  31402. var Mesh = /** @class */ (function (_super) {
  31403. __extends(Mesh, _super);
  31404. /**
  31405. * @constructor
  31406. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31407. * @param {Scene} scene The scene to add this mesh to.
  31408. * @param {Node} parent The parent of this mesh, if it has one
  31409. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31410. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31411. * When false, achieved by calling a clone(), also passing False.
  31412. * This will make creation of children, recursive.
  31413. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31414. */
  31415. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31416. if (scene === void 0) { scene = null; }
  31417. if (parent === void 0) { parent = null; }
  31418. if (source === void 0) { source = null; }
  31419. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31420. var _this = _super.call(this, name, scene) || this;
  31421. // Events
  31422. /**
  31423. * An event triggered before rendering the mesh
  31424. */
  31425. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31426. /**
  31427. * An event triggered after rendering the mesh
  31428. */
  31429. _this.onAfterRenderObservable = new BABYLON.Observable();
  31430. /**
  31431. * An event triggered before drawing the mesh
  31432. */
  31433. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31434. // Members
  31435. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31436. _this.instances = new Array();
  31437. _this._LODLevels = new Array();
  31438. _this._visibleInstances = {};
  31439. _this._renderIdForInstances = new Array();
  31440. _this._batchCache = new _InstancesBatch();
  31441. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31442. // Use by builder only to know what orientation were the mesh build in.
  31443. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31444. _this.overrideMaterialSideOrientation = null;
  31445. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31446. // Will be used to save a source mesh reference, If any
  31447. _this._source = null;
  31448. scene = _this.getScene();
  31449. if (source) {
  31450. // Geometry
  31451. if (source._geometry) {
  31452. source._geometry.applyToMesh(_this);
  31453. }
  31454. // Deep copy
  31455. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31456. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31457. // Source mesh
  31458. _this._source = source;
  31459. // Metadata
  31460. if (source.metadata && source.metadata.clone) {
  31461. _this.metadata = source.metadata.clone();
  31462. }
  31463. else {
  31464. _this.metadata = source.metadata;
  31465. }
  31466. // Tags
  31467. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31468. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31469. }
  31470. // Parent
  31471. _this.parent = source.parent;
  31472. // Pivot
  31473. _this.setPivotMatrix(source.getPivotMatrix());
  31474. _this.id = name + "." + source.id;
  31475. // Material
  31476. _this.material = source.material;
  31477. var index;
  31478. if (!doNotCloneChildren) {
  31479. // Children
  31480. var directDescendants = source.getDescendants(true);
  31481. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31482. var child = directDescendants[index_1];
  31483. if (child.clone) {
  31484. child.clone(name + "." + child.name, _this);
  31485. }
  31486. }
  31487. }
  31488. // Physics clone
  31489. var physicsEngine = _this.getScene().getPhysicsEngine();
  31490. if (clonePhysicsImpostor && physicsEngine) {
  31491. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31492. if (impostor) {
  31493. _this.physicsImpostor = impostor.clone(_this);
  31494. }
  31495. }
  31496. // Particles
  31497. for (index = 0; index < scene.particleSystems.length; index++) {
  31498. var system = scene.particleSystems[index];
  31499. if (system.emitter === source) {
  31500. system.clone(system.name, _this);
  31501. }
  31502. }
  31503. _this.refreshBoundingInfo();
  31504. _this.computeWorldMatrix(true);
  31505. }
  31506. // Parent
  31507. if (parent !== null) {
  31508. _this.parent = parent;
  31509. }
  31510. return _this;
  31511. }
  31512. Object.defineProperty(Mesh, "FRONTSIDE", {
  31513. /**
  31514. * Mesh side orientation : usually the external or front surface
  31515. */
  31516. get: function () {
  31517. return Mesh._FRONTSIDE;
  31518. },
  31519. enumerable: true,
  31520. configurable: true
  31521. });
  31522. Object.defineProperty(Mesh, "BACKSIDE", {
  31523. /**
  31524. * Mesh side orientation : usually the internal or back surface
  31525. */
  31526. get: function () {
  31527. return Mesh._BACKSIDE;
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31533. /**
  31534. * Mesh side orientation : both internal and external or front and back surfaces
  31535. */
  31536. get: function () {
  31537. return Mesh._DOUBLESIDE;
  31538. },
  31539. enumerable: true,
  31540. configurable: true
  31541. });
  31542. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31543. /**
  31544. * Mesh side orientation : by default, `FRONTSIDE`
  31545. */
  31546. get: function () {
  31547. return Mesh._DEFAULTSIDE;
  31548. },
  31549. enumerable: true,
  31550. configurable: true
  31551. });
  31552. Object.defineProperty(Mesh, "NO_CAP", {
  31553. /**
  31554. * Mesh cap setting : no cap
  31555. */
  31556. get: function () {
  31557. return Mesh._NO_CAP;
  31558. },
  31559. enumerable: true,
  31560. configurable: true
  31561. });
  31562. Object.defineProperty(Mesh, "CAP_START", {
  31563. /**
  31564. * Mesh cap setting : one cap at the beginning of the mesh
  31565. */
  31566. get: function () {
  31567. return Mesh._CAP_START;
  31568. },
  31569. enumerable: true,
  31570. configurable: true
  31571. });
  31572. Object.defineProperty(Mesh, "CAP_END", {
  31573. /**
  31574. * Mesh cap setting : one cap at the end of the mesh
  31575. */
  31576. get: function () {
  31577. return Mesh._CAP_END;
  31578. },
  31579. enumerable: true,
  31580. configurable: true
  31581. });
  31582. Object.defineProperty(Mesh, "CAP_ALL", {
  31583. /**
  31584. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31585. */
  31586. get: function () {
  31587. return Mesh._CAP_ALL;
  31588. },
  31589. enumerable: true,
  31590. configurable: true
  31591. });
  31592. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31593. set: function (callback) {
  31594. if (this._onBeforeDrawObserver) {
  31595. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31596. }
  31597. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31598. },
  31599. enumerable: true,
  31600. configurable: true
  31601. });
  31602. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31603. get: function () {
  31604. return this._morphTargetManager;
  31605. },
  31606. set: function (value) {
  31607. if (this._morphTargetManager === value) {
  31608. return;
  31609. }
  31610. this._morphTargetManager = value;
  31611. this._syncGeometryWithMorphTargetManager();
  31612. },
  31613. enumerable: true,
  31614. configurable: true
  31615. });
  31616. Object.defineProperty(Mesh.prototype, "source", {
  31617. get: function () {
  31618. return this._source;
  31619. },
  31620. enumerable: true,
  31621. configurable: true
  31622. });
  31623. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31624. get: function () {
  31625. return this._unIndexed;
  31626. },
  31627. set: function (value) {
  31628. if (this._unIndexed !== value) {
  31629. this._unIndexed = value;
  31630. this._markSubMeshesAsAttributesDirty();
  31631. }
  31632. },
  31633. enumerable: true,
  31634. configurable: true
  31635. });
  31636. // Methods
  31637. /**
  31638. * Returns the string "Mesh".
  31639. */
  31640. Mesh.prototype.getClassName = function () {
  31641. return "Mesh";
  31642. };
  31643. /**
  31644. * Returns a string.
  31645. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31646. */
  31647. Mesh.prototype.toString = function (fullDetails) {
  31648. var ret = _super.prototype.toString.call(this, fullDetails);
  31649. ret += ", n vertices: " + this.getTotalVertices();
  31650. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31651. if (this.animations) {
  31652. for (var i = 0; i < this.animations.length; i++) {
  31653. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31654. }
  31655. }
  31656. if (fullDetails) {
  31657. if (this._geometry) {
  31658. var ib = this.getIndices();
  31659. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31660. if (vb && ib) {
  31661. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31662. }
  31663. }
  31664. else {
  31665. ret += ", flat shading: UNKNOWN";
  31666. }
  31667. }
  31668. return ret;
  31669. };
  31670. Mesh.prototype._unBindEffect = function () {
  31671. _super.prototype._unBindEffect.call(this);
  31672. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31673. var instance = _a[_i];
  31674. instance._unBindEffect();
  31675. }
  31676. };
  31677. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31678. /**
  31679. * True if the mesh has some Levels Of Details (LOD).
  31680. * Returns a boolean.
  31681. */
  31682. get: function () {
  31683. return this._LODLevels.length > 0;
  31684. },
  31685. enumerable: true,
  31686. configurable: true
  31687. });
  31688. /**
  31689. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31690. * @returns an array of {BABYLON.MeshLODLevel}
  31691. */
  31692. Mesh.prototype.getLODLevels = function () {
  31693. return this._LODLevels;
  31694. };
  31695. Mesh.prototype._sortLODLevels = function () {
  31696. this._LODLevels.sort(function (a, b) {
  31697. if (a.distance < b.distance) {
  31698. return 1;
  31699. }
  31700. if (a.distance > b.distance) {
  31701. return -1;
  31702. }
  31703. return 0;
  31704. });
  31705. };
  31706. /**
  31707. * Add a mesh as LOD level triggered at the given distance.
  31708. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31709. * @param distance The distance from the center of the object to show this level
  31710. * @param mesh The mesh to be added as LOD level (can be null)
  31711. * @return This mesh (for chaining)
  31712. */
  31713. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31714. if (mesh && mesh._masterMesh) {
  31715. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31716. return this;
  31717. }
  31718. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31719. this._LODLevels.push(level);
  31720. if (mesh) {
  31721. mesh._masterMesh = this;
  31722. }
  31723. this._sortLODLevels();
  31724. return this;
  31725. };
  31726. /**
  31727. * Returns the LOD level mesh at the passed distance or null if not found.
  31728. * It is related to the method `addLODLevel(distance, mesh)`.
  31729. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31730. * Returns an object Mesh or `null`.
  31731. */
  31732. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31733. for (var index = 0; index < this._LODLevels.length; index++) {
  31734. var level = this._LODLevels[index];
  31735. if (level.distance === distance) {
  31736. return level.mesh;
  31737. }
  31738. }
  31739. return null;
  31740. };
  31741. /**
  31742. * Remove a mesh from the LOD array
  31743. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31744. * @param {Mesh} mesh The mesh to be removed.
  31745. * @return {Mesh} This mesh (for chaining)
  31746. */
  31747. Mesh.prototype.removeLODLevel = function (mesh) {
  31748. for (var index = 0; index < this._LODLevels.length; index++) {
  31749. if (this._LODLevels[index].mesh === mesh) {
  31750. this._LODLevels.splice(index, 1);
  31751. if (mesh) {
  31752. mesh._masterMesh = null;
  31753. }
  31754. }
  31755. }
  31756. this._sortLODLevels();
  31757. return this;
  31758. };
  31759. /**
  31760. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31761. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31762. */
  31763. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31764. if (!this._LODLevels || this._LODLevels.length === 0) {
  31765. return this;
  31766. }
  31767. var bSphere;
  31768. if (boundingSphere) {
  31769. bSphere = boundingSphere;
  31770. }
  31771. else {
  31772. var boundingInfo = this.getBoundingInfo();
  31773. bSphere = boundingInfo.boundingSphere;
  31774. }
  31775. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31776. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31777. if (this.onLODLevelSelection) {
  31778. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31779. }
  31780. return this;
  31781. }
  31782. for (var index = 0; index < this._LODLevels.length; index++) {
  31783. var level = this._LODLevels[index];
  31784. if (level.distance < distanceToCamera) {
  31785. if (level.mesh) {
  31786. level.mesh._preActivate();
  31787. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31788. }
  31789. if (this.onLODLevelSelection) {
  31790. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31791. }
  31792. return level.mesh;
  31793. }
  31794. }
  31795. if (this.onLODLevelSelection) {
  31796. this.onLODLevelSelection(distanceToCamera, this, this);
  31797. }
  31798. return this;
  31799. };
  31800. Object.defineProperty(Mesh.prototype, "geometry", {
  31801. /**
  31802. * Returns the mesh internal Geometry object.
  31803. */
  31804. get: function () {
  31805. return this._geometry;
  31806. },
  31807. enumerable: true,
  31808. configurable: true
  31809. });
  31810. /**
  31811. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31812. */
  31813. Mesh.prototype.getTotalVertices = function () {
  31814. if (this._geometry === null || this._geometry === undefined) {
  31815. return 0;
  31816. }
  31817. return this._geometry.getTotalVertices();
  31818. };
  31819. /**
  31820. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31821. * 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.
  31822. * You can force the copy with forceCopy === true
  31823. * Returns null if the mesh has no geometry or no vertex buffer.
  31824. * Possible `kind` values :
  31825. * - BABYLON.VertexBuffer.PositionKind
  31826. * - BABYLON.VertexBuffer.UVKind
  31827. * - BABYLON.VertexBuffer.UV2Kind
  31828. * - BABYLON.VertexBuffer.UV3Kind
  31829. * - BABYLON.VertexBuffer.UV4Kind
  31830. * - BABYLON.VertexBuffer.UV5Kind
  31831. * - BABYLON.VertexBuffer.UV6Kind
  31832. * - BABYLON.VertexBuffer.ColorKind
  31833. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31834. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31835. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31836. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31837. */
  31838. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31839. if (!this._geometry) {
  31840. return null;
  31841. }
  31842. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31843. };
  31844. /**
  31845. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31846. * Returns `null` if the mesh has no geometry.
  31847. * Possible `kind` values :
  31848. * - BABYLON.VertexBuffer.PositionKind
  31849. * - BABYLON.VertexBuffer.UVKind
  31850. * - BABYLON.VertexBuffer.UV2Kind
  31851. * - BABYLON.VertexBuffer.UV3Kind
  31852. * - BABYLON.VertexBuffer.UV4Kind
  31853. * - BABYLON.VertexBuffer.UV5Kind
  31854. * - BABYLON.VertexBuffer.UV6Kind
  31855. * - BABYLON.VertexBuffer.ColorKind
  31856. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31857. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31858. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31859. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31860. */
  31861. Mesh.prototype.getVertexBuffer = function (kind) {
  31862. if (!this._geometry) {
  31863. return null;
  31864. }
  31865. return this._geometry.getVertexBuffer(kind);
  31866. };
  31867. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31868. if (!this._geometry) {
  31869. if (this._delayInfo) {
  31870. return this._delayInfo.indexOf(kind) !== -1;
  31871. }
  31872. return false;
  31873. }
  31874. return this._geometry.isVerticesDataPresent(kind);
  31875. };
  31876. /**
  31877. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31878. * Possible `kind` values :
  31879. * - BABYLON.VertexBuffer.PositionKind
  31880. * - BABYLON.VertexBuffer.UVKind
  31881. * - BABYLON.VertexBuffer.UV2Kind
  31882. * - BABYLON.VertexBuffer.UV3Kind
  31883. * - BABYLON.VertexBuffer.UV4Kind
  31884. * - BABYLON.VertexBuffer.UV5Kind
  31885. * - BABYLON.VertexBuffer.UV6Kind
  31886. * - BABYLON.VertexBuffer.ColorKind
  31887. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31888. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31889. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31890. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31891. */
  31892. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31893. if (!this._geometry) {
  31894. if (this._delayInfo) {
  31895. return this._delayInfo.indexOf(kind) !== -1;
  31896. }
  31897. return false;
  31898. }
  31899. return this._geometry.isVertexBufferUpdatable(kind);
  31900. };
  31901. /**
  31902. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31903. * Possible `kind` values :
  31904. * - BABYLON.VertexBuffer.PositionKind
  31905. * - BABYLON.VertexBuffer.UVKind
  31906. * - BABYLON.VertexBuffer.UV2Kind
  31907. * - BABYLON.VertexBuffer.UV3Kind
  31908. * - BABYLON.VertexBuffer.UV4Kind
  31909. * - BABYLON.VertexBuffer.UV5Kind
  31910. * - BABYLON.VertexBuffer.UV6Kind
  31911. * - BABYLON.VertexBuffer.ColorKind
  31912. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31913. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31914. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31915. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31916. */
  31917. Mesh.prototype.getVerticesDataKinds = function () {
  31918. if (!this._geometry) {
  31919. var result = new Array();
  31920. if (this._delayInfo) {
  31921. this._delayInfo.forEach(function (kind, index, array) {
  31922. result.push(kind);
  31923. });
  31924. }
  31925. return result;
  31926. }
  31927. return this._geometry.getVerticesDataKinds();
  31928. };
  31929. /**
  31930. * Returns a positive integer : the total number of indices in this mesh geometry.
  31931. * Returns zero if the mesh has no geometry.
  31932. */
  31933. Mesh.prototype.getTotalIndices = function () {
  31934. if (!this._geometry) {
  31935. return 0;
  31936. }
  31937. return this._geometry.getTotalIndices();
  31938. };
  31939. /**
  31940. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31941. * If the parameter `copyWhenShared` is 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.
  31942. * Returns an empty array if the mesh has no geometry.
  31943. */
  31944. Mesh.prototype.getIndices = function (copyWhenShared) {
  31945. if (!this._geometry) {
  31946. return [];
  31947. }
  31948. return this._geometry.getIndices(copyWhenShared);
  31949. };
  31950. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31951. get: function () {
  31952. return this._masterMesh !== null && this._masterMesh !== undefined;
  31953. },
  31954. enumerable: true,
  31955. configurable: true
  31956. });
  31957. /**
  31958. * Determine if the current mesh is ready to be rendered
  31959. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31960. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31961. * @returns true if all associated assets are ready (material, textures, shaders)
  31962. */
  31963. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31964. if (completeCheck === void 0) { completeCheck = false; }
  31965. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31966. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31967. return false;
  31968. }
  31969. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31970. return false;
  31971. }
  31972. if (!this.subMeshes || this.subMeshes.length === 0) {
  31973. return true;
  31974. }
  31975. if (!completeCheck) {
  31976. return true;
  31977. }
  31978. var engine = this.getEngine();
  31979. var scene = this.getScene();
  31980. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31981. this.computeWorldMatrix();
  31982. var mat = this.material || scene.defaultMaterial;
  31983. if (mat) {
  31984. if (mat.storeEffectOnSubMeshes) {
  31985. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31986. var subMesh = _a[_i];
  31987. var effectiveMaterial = subMesh.getMaterial();
  31988. if (effectiveMaterial) {
  31989. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31990. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31991. return false;
  31992. }
  31993. }
  31994. else {
  31995. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31996. return false;
  31997. }
  31998. }
  31999. }
  32000. }
  32001. }
  32002. else {
  32003. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32004. return false;
  32005. }
  32006. }
  32007. }
  32008. // Shadows
  32009. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32010. var light = _c[_b];
  32011. var generator = light.getShadowGenerator();
  32012. if (generator) {
  32013. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32014. var subMesh = _e[_d];
  32015. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32016. return false;
  32017. }
  32018. }
  32019. }
  32020. }
  32021. // LOD
  32022. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32023. var lod = _g[_f];
  32024. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32025. return false;
  32026. }
  32027. }
  32028. return true;
  32029. };
  32030. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32031. /**
  32032. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32033. * This property is pertinent only for updatable parametric shapes.
  32034. */
  32035. get: function () {
  32036. return this._areNormalsFrozen;
  32037. },
  32038. enumerable: true,
  32039. configurable: true
  32040. });
  32041. /**
  32042. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32043. * It has no effect at all on other shapes.
  32044. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32045. * Returns the Mesh.
  32046. */
  32047. Mesh.prototype.freezeNormals = function () {
  32048. this._areNormalsFrozen = true;
  32049. return this;
  32050. };
  32051. /**
  32052. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32053. * It has no effect at all on other shapes.
  32054. * It reactivates the mesh normals computation if it was previously frozen.
  32055. * Returns the Mesh.
  32056. */
  32057. Mesh.prototype.unfreezeNormals = function () {
  32058. this._areNormalsFrozen = false;
  32059. return this;
  32060. };
  32061. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32062. /**
  32063. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32064. */
  32065. set: function (count) {
  32066. this._overridenInstanceCount = count;
  32067. },
  32068. enumerable: true,
  32069. configurable: true
  32070. });
  32071. // Methods
  32072. Mesh.prototype._preActivate = function () {
  32073. var sceneRenderId = this.getScene().getRenderId();
  32074. if (this._preActivateId === sceneRenderId) {
  32075. return this;
  32076. }
  32077. this._preActivateId = sceneRenderId;
  32078. this._visibleInstances = null;
  32079. return this;
  32080. };
  32081. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32082. if (this._visibleInstances) {
  32083. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32084. }
  32085. return this;
  32086. };
  32087. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32088. if (!this._visibleInstances) {
  32089. this._visibleInstances = {};
  32090. this._visibleInstances.defaultRenderId = renderId;
  32091. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32092. }
  32093. if (!this._visibleInstances[renderId]) {
  32094. this._visibleInstances[renderId] = new Array();
  32095. }
  32096. this._visibleInstances[renderId].push(instance);
  32097. return this;
  32098. };
  32099. /**
  32100. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32101. * This means the mesh underlying bounding box and sphere are recomputed.
  32102. * Returns the Mesh.
  32103. */
  32104. Mesh.prototype.refreshBoundingInfo = function () {
  32105. return this._refreshBoundingInfo(false);
  32106. };
  32107. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32108. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32109. return this;
  32110. }
  32111. var data = this._getPositionData(applySkeleton);
  32112. if (data) {
  32113. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32114. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32115. }
  32116. if (this.subMeshes) {
  32117. for (var index = 0; index < this.subMeshes.length; index++) {
  32118. this.subMeshes[index].refreshBoundingInfo();
  32119. }
  32120. }
  32121. this._updateBoundingInfo();
  32122. return this;
  32123. };
  32124. Mesh.prototype._getPositionData = function (applySkeleton) {
  32125. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32126. if (data && applySkeleton && this.skeleton) {
  32127. data = BABYLON.Tools.Slice(data);
  32128. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32129. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32130. if (matricesWeightsData && matricesIndicesData) {
  32131. var needExtras = this.numBoneInfluencers > 4;
  32132. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32133. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32134. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32135. var tempVector = BABYLON.Tmp.Vector3[0];
  32136. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32137. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32138. var matWeightIdx = 0;
  32139. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32140. finalMatrix.reset();
  32141. var inf;
  32142. var weight;
  32143. for (inf = 0; inf < 4; inf++) {
  32144. weight = matricesWeightsData[matWeightIdx + inf];
  32145. if (weight <= 0)
  32146. break;
  32147. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32148. finalMatrix.addToSelf(tempMatrix);
  32149. }
  32150. if (needExtras) {
  32151. for (inf = 0; inf < 4; inf++) {
  32152. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32153. if (weight <= 0)
  32154. break;
  32155. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32156. finalMatrix.addToSelf(tempMatrix);
  32157. }
  32158. }
  32159. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32160. tempVector.toArray(data, index);
  32161. }
  32162. }
  32163. }
  32164. return data;
  32165. };
  32166. Mesh.prototype._createGlobalSubMesh = function (force) {
  32167. var totalVertices = this.getTotalVertices();
  32168. if (!totalVertices || !this.getIndices()) {
  32169. return null;
  32170. }
  32171. // Check if we need to recreate the submeshes
  32172. if (this.subMeshes && this.subMeshes.length > 0) {
  32173. var ib = this.getIndices();
  32174. if (!ib) {
  32175. return null;
  32176. }
  32177. var totalIndices = ib.length;
  32178. var needToRecreate = false;
  32179. if (force) {
  32180. needToRecreate = true;
  32181. }
  32182. else {
  32183. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32184. var submesh = _a[_i];
  32185. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32186. needToRecreate = true;
  32187. break;
  32188. }
  32189. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32190. needToRecreate = true;
  32191. break;
  32192. }
  32193. }
  32194. }
  32195. if (!needToRecreate) {
  32196. return this.subMeshes[0];
  32197. }
  32198. }
  32199. this.releaseSubMeshes();
  32200. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32201. };
  32202. Mesh.prototype.subdivide = function (count) {
  32203. if (count < 1) {
  32204. return;
  32205. }
  32206. var totalIndices = this.getTotalIndices();
  32207. var subdivisionSize = (totalIndices / count) | 0;
  32208. var offset = 0;
  32209. // Ensure that subdivisionSize is a multiple of 3
  32210. while (subdivisionSize % 3 !== 0) {
  32211. subdivisionSize++;
  32212. }
  32213. this.releaseSubMeshes();
  32214. for (var index = 0; index < count; index++) {
  32215. if (offset >= totalIndices) {
  32216. break;
  32217. }
  32218. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32219. offset += subdivisionSize;
  32220. }
  32221. this.synchronizeInstances();
  32222. };
  32223. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32224. if (updatable === void 0) { updatable = false; }
  32225. if (!this._geometry) {
  32226. var vertexData = new BABYLON.VertexData();
  32227. vertexData.set(data, kind);
  32228. var scene = this.getScene();
  32229. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32230. }
  32231. else {
  32232. this._geometry.setVerticesData(kind, data, updatable, stride);
  32233. }
  32234. return this;
  32235. };
  32236. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32237. if (updatable === void 0) { updatable = true; }
  32238. var vb = this.getVertexBuffer(kind);
  32239. if (!vb || vb.isUpdatable() === updatable) {
  32240. return;
  32241. }
  32242. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32243. };
  32244. /**
  32245. * Sets the mesh VertexBuffer.
  32246. * Returns the Mesh.
  32247. */
  32248. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32249. if (!this._geometry) {
  32250. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32251. }
  32252. this._geometry.setVerticesBuffer(buffer);
  32253. return this;
  32254. };
  32255. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32256. if (!this._geometry) {
  32257. return this;
  32258. }
  32259. if (!makeItUnique) {
  32260. this._geometry.updateVerticesData(kind, data, updateExtends);
  32261. }
  32262. else {
  32263. this.makeGeometryUnique();
  32264. this.updateVerticesData(kind, data, updateExtends, false);
  32265. }
  32266. return this;
  32267. };
  32268. /**
  32269. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32270. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32271. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32272. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32273. * Returns the Mesh.
  32274. */
  32275. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32276. if (computeNormals === void 0) { computeNormals = true; }
  32277. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32278. if (!positions) {
  32279. return this;
  32280. }
  32281. positionFunction(positions);
  32282. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32283. if (computeNormals) {
  32284. var indices = this.getIndices();
  32285. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32286. if (!normals) {
  32287. return this;
  32288. }
  32289. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32290. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32291. }
  32292. return this;
  32293. };
  32294. /**
  32295. * Creates a un-shared specific occurence of the geometry for the mesh.
  32296. * Returns the Mesh.
  32297. */
  32298. Mesh.prototype.makeGeometryUnique = function () {
  32299. if (!this._geometry) {
  32300. return this;
  32301. }
  32302. var oldGeometry = this._geometry;
  32303. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32304. oldGeometry.releaseForMesh(this, true);
  32305. geometry.applyToMesh(this);
  32306. return this;
  32307. };
  32308. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32309. if (totalVertices === void 0) { totalVertices = null; }
  32310. if (updatable === void 0) { updatable = false; }
  32311. if (!this._geometry) {
  32312. var vertexData = new BABYLON.VertexData();
  32313. vertexData.indices = indices;
  32314. var scene = this.getScene();
  32315. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32316. }
  32317. else {
  32318. this._geometry.setIndices(indices, totalVertices, updatable);
  32319. }
  32320. return this;
  32321. };
  32322. /**
  32323. * Update the current index buffer
  32324. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32325. * Returns the Mesh.
  32326. */
  32327. Mesh.prototype.updateIndices = function (indices, offset) {
  32328. if (!this._geometry) {
  32329. return this;
  32330. }
  32331. this._geometry.updateIndices(indices, offset);
  32332. return this;
  32333. };
  32334. /**
  32335. * Invert the geometry to move from a right handed system to a left handed one.
  32336. * Returns the Mesh.
  32337. */
  32338. Mesh.prototype.toLeftHanded = function () {
  32339. if (!this._geometry) {
  32340. return this;
  32341. }
  32342. this._geometry.toLeftHanded();
  32343. return this;
  32344. };
  32345. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32346. if (!this._geometry) {
  32347. return this;
  32348. }
  32349. var engine = this.getScene().getEngine();
  32350. // Wireframe
  32351. var indexToBind;
  32352. if (this._unIndexed) {
  32353. indexToBind = null;
  32354. }
  32355. else {
  32356. switch (fillMode) {
  32357. case BABYLON.Material.PointFillMode:
  32358. indexToBind = null;
  32359. break;
  32360. case BABYLON.Material.WireFrameFillMode:
  32361. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32362. break;
  32363. default:
  32364. case BABYLON.Material.TriangleFillMode:
  32365. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32366. break;
  32367. }
  32368. }
  32369. // VBOs
  32370. this._geometry._bind(effect, indexToBind);
  32371. return this;
  32372. };
  32373. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32374. if (alternate === void 0) { alternate = false; }
  32375. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32376. return this;
  32377. }
  32378. this.onBeforeDrawObservable.notifyObservers(this);
  32379. var scene = this.getScene();
  32380. var engine = scene.getEngine();
  32381. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32382. // or triangles as points
  32383. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32384. }
  32385. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32386. // Triangles as wireframe
  32387. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32388. }
  32389. else {
  32390. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32391. }
  32392. if (scene._isAlternateRenderingEnabled && !alternate) {
  32393. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32394. if (!effect || !scene.activeCamera) {
  32395. return this;
  32396. }
  32397. scene._switchToAlternateCameraConfiguration(true);
  32398. this._effectiveMaterial.bindView(effect);
  32399. this._effectiveMaterial.bindViewProjection(effect);
  32400. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32401. this._draw(subMesh, fillMode, instancesCount, true);
  32402. engine.setViewport(scene.activeCamera.viewport);
  32403. scene._switchToAlternateCameraConfiguration(false);
  32404. this._effectiveMaterial.bindView(effect);
  32405. this._effectiveMaterial.bindViewProjection(effect);
  32406. }
  32407. return this;
  32408. };
  32409. /**
  32410. * Registers for this mesh a javascript function called just before the rendering process.
  32411. * This function is passed the current mesh.
  32412. * Return the Mesh.
  32413. */
  32414. Mesh.prototype.registerBeforeRender = function (func) {
  32415. this.onBeforeRenderObservable.add(func);
  32416. return this;
  32417. };
  32418. /**
  32419. * Disposes a previously registered javascript function called before the rendering.
  32420. * This function is passed the current mesh.
  32421. * Returns the Mesh.
  32422. */
  32423. Mesh.prototype.unregisterBeforeRender = function (func) {
  32424. this.onBeforeRenderObservable.removeCallback(func);
  32425. return this;
  32426. };
  32427. /**
  32428. * Registers for this mesh a javascript function called just after the rendering is complete.
  32429. * This function is passed the current mesh.
  32430. * Returns the Mesh.
  32431. */
  32432. Mesh.prototype.registerAfterRender = function (func) {
  32433. this.onAfterRenderObservable.add(func);
  32434. return this;
  32435. };
  32436. /**
  32437. * Disposes a previously registered javascript function called after the rendering.
  32438. * This function is passed the current mesh.
  32439. * Return the Mesh.
  32440. */
  32441. Mesh.prototype.unregisterAfterRender = function (func) {
  32442. this.onAfterRenderObservable.removeCallback(func);
  32443. return this;
  32444. };
  32445. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32446. var scene = this.getScene();
  32447. this._batchCache.mustReturn = false;
  32448. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32449. this._batchCache.visibleInstances[subMeshId] = null;
  32450. if (this._visibleInstances) {
  32451. var currentRenderId = scene.getRenderId();
  32452. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32453. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32454. var selfRenderId = this._renderId;
  32455. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32456. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32457. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32458. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32459. }
  32460. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32461. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32462. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32463. this._batchCache.mustReturn = true;
  32464. return this._batchCache;
  32465. }
  32466. if (currentRenderId !== selfRenderId) {
  32467. this._batchCache.renderSelf[subMeshId] = false;
  32468. }
  32469. }
  32470. this._renderIdForInstances[subMeshId] = currentRenderId;
  32471. }
  32472. return this._batchCache;
  32473. };
  32474. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32475. var visibleInstances = batch.visibleInstances[subMesh._id];
  32476. if (!visibleInstances) {
  32477. return this;
  32478. }
  32479. var matricesCount = visibleInstances.length + 1;
  32480. var bufferSize = matricesCount * 16 * 4;
  32481. var currentInstancesBufferSize = this._instancesBufferSize;
  32482. var instancesBuffer = this._instancesBuffer;
  32483. while (this._instancesBufferSize < bufferSize) {
  32484. this._instancesBufferSize *= 2;
  32485. }
  32486. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32487. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32488. }
  32489. var offset = 0;
  32490. var instancesCount = 0;
  32491. var world = this.getWorldMatrix();
  32492. if (batch.renderSelf[subMesh._id]) {
  32493. world.copyToArray(this._instancesData, offset);
  32494. offset += 16;
  32495. instancesCount++;
  32496. }
  32497. if (visibleInstances) {
  32498. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32499. var instance = visibleInstances[instanceIndex];
  32500. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32501. offset += 16;
  32502. instancesCount++;
  32503. }
  32504. }
  32505. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32506. if (instancesBuffer) {
  32507. instancesBuffer.dispose();
  32508. }
  32509. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32510. this._instancesBuffer = instancesBuffer;
  32511. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32512. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32513. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32514. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32515. }
  32516. else {
  32517. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32518. }
  32519. this._bind(subMesh, effect, fillMode);
  32520. this._draw(subMesh, fillMode, instancesCount);
  32521. engine.unbindInstanceAttributes();
  32522. return this;
  32523. };
  32524. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32525. var scene = this.getScene();
  32526. var engine = scene.getEngine();
  32527. if (hardwareInstancedRendering) {
  32528. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32529. }
  32530. else {
  32531. if (batch.renderSelf[subMesh._id]) {
  32532. // Draw
  32533. if (onBeforeDraw) {
  32534. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32535. }
  32536. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32537. }
  32538. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32539. if (visibleInstancesForSubMesh) {
  32540. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32541. var instance = visibleInstancesForSubMesh[instanceIndex];
  32542. // World
  32543. var world = instance.getWorldMatrix();
  32544. if (onBeforeDraw) {
  32545. onBeforeDraw(true, world, effectiveMaterial);
  32546. }
  32547. // Draw
  32548. this._draw(subMesh, fillMode);
  32549. }
  32550. }
  32551. }
  32552. return this;
  32553. };
  32554. /**
  32555. * Triggers the draw call for the mesh.
  32556. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32557. * Returns the Mesh.
  32558. */
  32559. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32560. this._checkOcclusionQuery();
  32561. if (this._isOccluded) {
  32562. return this;
  32563. }
  32564. var scene = this.getScene();
  32565. // Managing instances
  32566. var batch = this._getInstancesRenderList(subMesh._id);
  32567. if (batch.mustReturn) {
  32568. return this;
  32569. }
  32570. // Checking geometry state
  32571. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32572. return this;
  32573. }
  32574. this.onBeforeRenderObservable.notifyObservers(this);
  32575. var engine = scene.getEngine();
  32576. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32577. // Material
  32578. var material = subMesh.getMaterial();
  32579. if (!material) {
  32580. return this;
  32581. }
  32582. this._effectiveMaterial = material;
  32583. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32584. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32585. return this;
  32586. }
  32587. }
  32588. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32589. return this;
  32590. }
  32591. // Alpha mode
  32592. if (enableAlphaMode) {
  32593. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32594. }
  32595. // Outline - step 1
  32596. var savedDepthWrite = engine.getDepthWrite();
  32597. if (this.renderOutline) {
  32598. engine.setDepthWrite(false);
  32599. scene.getOutlineRenderer().render(subMesh, batch);
  32600. engine.setDepthWrite(savedDepthWrite);
  32601. }
  32602. var effect;
  32603. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32604. effect = subMesh.effect;
  32605. }
  32606. else {
  32607. effect = this._effectiveMaterial.getEffect();
  32608. }
  32609. if (!effect) {
  32610. return this;
  32611. }
  32612. var sideOrientation = this.overrideMaterialSideOrientation;
  32613. if (sideOrientation == null) {
  32614. sideOrientation = this._effectiveMaterial.sideOrientation;
  32615. if (this._getWorldMatrixDeterminant() < 0) {
  32616. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32617. }
  32618. }
  32619. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32620. if (this._effectiveMaterial.forceDepthWrite) {
  32621. engine.setDepthWrite(true);
  32622. }
  32623. // Bind
  32624. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32625. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32626. this._bind(subMesh, effect, fillMode);
  32627. }
  32628. var world = this.getWorldMatrix();
  32629. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32630. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32631. }
  32632. else {
  32633. this._effectiveMaterial.bind(world, this);
  32634. }
  32635. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32636. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32637. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32638. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32639. }
  32640. // Draw
  32641. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32642. // Unbind
  32643. this._effectiveMaterial.unbind();
  32644. // Outline - step 2
  32645. if (this.renderOutline && savedDepthWrite) {
  32646. engine.setDepthWrite(true);
  32647. engine.setColorWrite(false);
  32648. scene.getOutlineRenderer().render(subMesh, batch);
  32649. engine.setColorWrite(true);
  32650. }
  32651. // Overlay
  32652. if (this.renderOverlay) {
  32653. var currentMode = engine.getAlphaMode();
  32654. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32655. scene.getOutlineRenderer().render(subMesh, batch, true);
  32656. engine.setAlphaMode(currentMode);
  32657. }
  32658. this.onAfterRenderObservable.notifyObservers(this);
  32659. return this;
  32660. };
  32661. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32662. if (isInstance && effectiveMaterial) {
  32663. effectiveMaterial.bindOnlyWorldMatrix(world);
  32664. }
  32665. };
  32666. /**
  32667. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32668. */
  32669. Mesh.prototype.getEmittedParticleSystems = function () {
  32670. var results = new Array();
  32671. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32672. var particleSystem = this.getScene().particleSystems[index];
  32673. if (particleSystem.emitter === this) {
  32674. results.push(particleSystem);
  32675. }
  32676. }
  32677. return results;
  32678. };
  32679. /**
  32680. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32681. */
  32682. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32683. var results = new Array();
  32684. var descendants = this.getDescendants();
  32685. descendants.push(this);
  32686. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32687. var particleSystem = this.getScene().particleSystems[index];
  32688. var emitter = particleSystem.emitter;
  32689. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32690. results.push(particleSystem);
  32691. }
  32692. }
  32693. return results;
  32694. };
  32695. /**
  32696. * Normalize matrix weights so that all vertices have a total weight set to 1
  32697. */
  32698. Mesh.prototype.cleanMatrixWeights = function () {
  32699. var epsilon = 1e-3;
  32700. var noInfluenceBoneIndex = 0.0;
  32701. if (this.skeleton) {
  32702. noInfluenceBoneIndex = this.skeleton.bones.length;
  32703. }
  32704. else {
  32705. return;
  32706. }
  32707. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32708. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32709. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32710. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32711. var influencers = this.numBoneInfluencers;
  32712. var size = matricesWeights.length;
  32713. for (var i = 0; i < size; i += 4) {
  32714. var weight = 0.0;
  32715. var firstZeroWeight = -1;
  32716. for (var j = 0; j < 4; j++) {
  32717. var w = matricesWeights[i + j];
  32718. weight += w;
  32719. if (w < epsilon && firstZeroWeight < 0) {
  32720. firstZeroWeight = j;
  32721. }
  32722. }
  32723. if (matricesWeightsExtra) {
  32724. for (var j = 0; j < 4; j++) {
  32725. var w = matricesWeightsExtra[i + j];
  32726. weight += w;
  32727. if (w < epsilon && firstZeroWeight < 0) {
  32728. firstZeroWeight = j + 4;
  32729. }
  32730. }
  32731. }
  32732. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32733. firstZeroWeight = influencers - 1;
  32734. }
  32735. if (weight > epsilon) {
  32736. var mweight = 1.0 / weight;
  32737. for (var j = 0; j < 4; j++) {
  32738. matricesWeights[i + j] *= mweight;
  32739. }
  32740. if (matricesWeightsExtra) {
  32741. for (var j = 0; j < 4; j++) {
  32742. matricesWeightsExtra[i + j] *= mweight;
  32743. }
  32744. }
  32745. }
  32746. else {
  32747. if (firstZeroWeight >= 4) {
  32748. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32749. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32750. }
  32751. else {
  32752. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32753. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32754. }
  32755. }
  32756. }
  32757. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32758. if (matricesIndicesExtra) {
  32759. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32760. }
  32761. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32762. if (matricesWeightsExtra) {
  32763. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32764. }
  32765. };
  32766. Mesh.prototype._checkDelayState = function () {
  32767. var scene = this.getScene();
  32768. if (this._geometry) {
  32769. this._geometry.load(scene);
  32770. }
  32771. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32772. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32773. this._queueLoad(scene);
  32774. }
  32775. return this;
  32776. };
  32777. Mesh.prototype._queueLoad = function (scene) {
  32778. var _this = this;
  32779. scene._addPendingData(this);
  32780. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32781. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32782. if (data instanceof ArrayBuffer) {
  32783. _this._delayLoadingFunction(data, _this);
  32784. }
  32785. else {
  32786. _this._delayLoadingFunction(JSON.parse(data), _this);
  32787. }
  32788. _this.instances.forEach(function (instance) {
  32789. instance._syncSubMeshes();
  32790. });
  32791. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32792. scene._removePendingData(_this);
  32793. }, function () { }, scene.database, getBinaryData);
  32794. return this;
  32795. };
  32796. /**
  32797. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32798. */
  32799. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32800. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32801. return false;
  32802. }
  32803. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32804. return false;
  32805. }
  32806. this._checkDelayState();
  32807. return true;
  32808. };
  32809. /**
  32810. * Sets the mesh material by the material or multiMaterial `id` property.
  32811. * The material `id` is a string identifying the material or the multiMaterial.
  32812. * This method returns the Mesh.
  32813. */
  32814. Mesh.prototype.setMaterialByID = function (id) {
  32815. var materials = this.getScene().materials;
  32816. var index;
  32817. for (index = materials.length - 1; index > -1; index--) {
  32818. if (materials[index].id === id) {
  32819. this.material = materials[index];
  32820. return this;
  32821. }
  32822. }
  32823. // Multi
  32824. var multiMaterials = this.getScene().multiMaterials;
  32825. for (index = multiMaterials.length - 1; index > -1; index--) {
  32826. if (multiMaterials[index].id === id) {
  32827. this.material = multiMaterials[index];
  32828. return this;
  32829. }
  32830. }
  32831. return this;
  32832. };
  32833. /**
  32834. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32835. */
  32836. Mesh.prototype.getAnimatables = function () {
  32837. var results = new Array();
  32838. if (this.material) {
  32839. results.push(this.material);
  32840. }
  32841. if (this.skeleton) {
  32842. results.push(this.skeleton);
  32843. }
  32844. return results;
  32845. };
  32846. /**
  32847. * Modifies the mesh geometry according to the passed transformation matrix.
  32848. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32849. * The mesh normals are modified accordingly the same transformation.
  32850. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32851. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32852. * Returns the Mesh.
  32853. */
  32854. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32855. // Position
  32856. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32857. return this;
  32858. }
  32859. var submeshes = this.subMeshes.splice(0);
  32860. this._resetPointsArrayCache();
  32861. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32862. var temp = new Array();
  32863. var index;
  32864. for (index = 0; index < data.length; index += 3) {
  32865. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32866. }
  32867. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32868. // Normals
  32869. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32870. return this;
  32871. }
  32872. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32873. temp = [];
  32874. for (index = 0; index < data.length; index += 3) {
  32875. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32876. }
  32877. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32878. // flip faces?
  32879. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32880. this.flipFaces();
  32881. }
  32882. // Restore submeshes
  32883. this.releaseSubMeshes();
  32884. this.subMeshes = submeshes;
  32885. return this;
  32886. };
  32887. /**
  32888. * Modifies the mesh geometry according to its own current World Matrix.
  32889. * The mesh World Matrix is then reset.
  32890. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32891. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32892. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32893. * Returns the Mesh.
  32894. */
  32895. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32896. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32897. this.scaling.copyFromFloats(1, 1, 1);
  32898. this.position.copyFromFloats(0, 0, 0);
  32899. this.rotation.copyFromFloats(0, 0, 0);
  32900. //only if quaternion is already set
  32901. if (this.rotationQuaternion) {
  32902. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32903. }
  32904. this._worldMatrix = BABYLON.Matrix.Identity();
  32905. return this;
  32906. };
  32907. Object.defineProperty(Mesh.prototype, "_positions", {
  32908. // Cache
  32909. get: function () {
  32910. if (this._geometry) {
  32911. return this._geometry._positions;
  32912. }
  32913. return null;
  32914. },
  32915. enumerable: true,
  32916. configurable: true
  32917. });
  32918. Mesh.prototype._resetPointsArrayCache = function () {
  32919. if (this._geometry) {
  32920. this._geometry._resetPointsArrayCache();
  32921. }
  32922. return this;
  32923. };
  32924. Mesh.prototype._generatePointsArray = function () {
  32925. if (this._geometry) {
  32926. return this._geometry._generatePointsArray();
  32927. }
  32928. return false;
  32929. };
  32930. /**
  32931. * Returns a new Mesh object generated from the current mesh properties.
  32932. * This method must not get confused with createInstance().
  32933. * The parameter `name` is a string, the name given to the new mesh.
  32934. * The optional parameter `newParent` can be any Node object (default `null`).
  32935. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32936. * 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.
  32937. */
  32938. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32939. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32940. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32941. };
  32942. /**
  32943. * Releases resources associated with this mesh.
  32944. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32945. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32946. */
  32947. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32948. var _this = this;
  32949. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32950. this.morphTargetManager = null;
  32951. if (this._geometry) {
  32952. this._geometry.releaseForMesh(this, true);
  32953. }
  32954. // Sources
  32955. var meshes = this.getScene().meshes;
  32956. meshes.forEach(function (abstractMesh) {
  32957. var mesh = abstractMesh;
  32958. if (mesh._source && mesh._source === _this) {
  32959. mesh._source = null;
  32960. }
  32961. });
  32962. this._source = null;
  32963. // Instances
  32964. if (this._instancesBuffer) {
  32965. this._instancesBuffer.dispose();
  32966. this._instancesBuffer = null;
  32967. }
  32968. while (this.instances.length) {
  32969. this.instances[0].dispose();
  32970. }
  32971. // Effect layers.
  32972. var effectLayers = this.getScene().effectLayers;
  32973. for (var i = 0; i < effectLayers.length; i++) {
  32974. var effectLayer = effectLayers[i];
  32975. if (effectLayer) {
  32976. effectLayer._disposeMesh(this);
  32977. }
  32978. }
  32979. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32980. };
  32981. /**
  32982. * Modifies the mesh geometry according to a displacement map.
  32983. * 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.
  32984. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32985. * This method returns nothing.
  32986. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32987. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32988. * The parameter `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.
  32989. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32990. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32991. *
  32992. * Returns the Mesh.
  32993. */
  32994. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32995. var _this = this;
  32996. var scene = this.getScene();
  32997. var onload = function (img) {
  32998. // Getting height map data
  32999. var canvas = document.createElement("canvas");
  33000. var context = canvas.getContext("2d");
  33001. var heightMapWidth = img.width;
  33002. var heightMapHeight = img.height;
  33003. canvas.width = heightMapWidth;
  33004. canvas.height = heightMapHeight;
  33005. context.drawImage(img, 0, 0);
  33006. // Create VertexData from map data
  33007. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33008. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33009. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33010. //execute success callback, if set
  33011. if (onSuccess) {
  33012. onSuccess(_this);
  33013. }
  33014. };
  33015. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33016. return this;
  33017. };
  33018. /**
  33019. * Modifies the mesh geometry according to a displacementMap buffer.
  33020. * 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.
  33021. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33022. * This method returns nothing.
  33023. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33024. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33025. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33026. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33027. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33028. *
  33029. * Returns the Mesh.
  33030. */
  33031. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33032. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33033. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33034. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33035. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33036. return this;
  33037. }
  33038. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33039. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33040. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33041. var position = BABYLON.Vector3.Zero();
  33042. var normal = BABYLON.Vector3.Zero();
  33043. var uv = BABYLON.Vector2.Zero();
  33044. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33045. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33046. for (var index = 0; index < positions.length; index += 3) {
  33047. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33048. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33049. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33050. // Compute height
  33051. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33052. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33053. var pos = (u + v * heightMapWidth) * 4;
  33054. var r = buffer[pos] / 255.0;
  33055. var g = buffer[pos + 1] / 255.0;
  33056. var b = buffer[pos + 2] / 255.0;
  33057. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33058. normal.normalize();
  33059. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33060. position = position.add(normal);
  33061. position.toArray(positions, index);
  33062. }
  33063. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33064. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33065. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33066. return this;
  33067. };
  33068. /**
  33069. * Modify the mesh to get a flat shading rendering.
  33070. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33071. * This method returns the Mesh.
  33072. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33073. */
  33074. Mesh.prototype.convertToFlatShadedMesh = function () {
  33075. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33076. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33077. var kinds = this.getVerticesDataKinds();
  33078. var vbs = {};
  33079. var data = {};
  33080. var newdata = {};
  33081. var updatableNormals = false;
  33082. var kindIndex;
  33083. var kind;
  33084. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33085. kind = kinds[kindIndex];
  33086. var vertexBuffer = this.getVertexBuffer(kind);
  33087. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33088. updatableNormals = vertexBuffer.isUpdatable();
  33089. kinds.splice(kindIndex, 1);
  33090. kindIndex--;
  33091. continue;
  33092. }
  33093. vbs[kind] = vertexBuffer;
  33094. data[kind] = vbs[kind].getData();
  33095. newdata[kind] = [];
  33096. }
  33097. // Save previous submeshes
  33098. var previousSubmeshes = this.subMeshes.slice(0);
  33099. var indices = this.getIndices();
  33100. var totalIndices = this.getTotalIndices();
  33101. // Generating unique vertices per face
  33102. var index;
  33103. for (index = 0; index < totalIndices; index++) {
  33104. var vertexIndex = indices[index];
  33105. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33106. kind = kinds[kindIndex];
  33107. var stride = vbs[kind].getStrideSize();
  33108. for (var offset = 0; offset < stride; offset++) {
  33109. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33110. }
  33111. }
  33112. }
  33113. // Updating faces & normal
  33114. var normals = [];
  33115. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33116. for (index = 0; index < totalIndices; index += 3) {
  33117. indices[index] = index;
  33118. indices[index + 1] = index + 1;
  33119. indices[index + 2] = index + 2;
  33120. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33121. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33122. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33123. var p1p2 = p1.subtract(p2);
  33124. var p3p2 = p3.subtract(p2);
  33125. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33126. // Store same normals for every vertex
  33127. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33128. normals.push(normal.x);
  33129. normals.push(normal.y);
  33130. normals.push(normal.z);
  33131. }
  33132. }
  33133. this.setIndices(indices);
  33134. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33135. // Updating vertex buffers
  33136. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33137. kind = kinds[kindIndex];
  33138. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33139. }
  33140. // Updating submeshes
  33141. this.releaseSubMeshes();
  33142. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33143. var previousOne = previousSubmeshes[submeshIndex];
  33144. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33145. }
  33146. this.synchronizeInstances();
  33147. return this;
  33148. };
  33149. /**
  33150. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33151. * In other words, more vertices, no more indices and a single bigger VBO.
  33152. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33153. * Returns the Mesh.
  33154. */
  33155. Mesh.prototype.convertToUnIndexedMesh = function () {
  33156. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33157. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33158. var kinds = this.getVerticesDataKinds();
  33159. var vbs = {};
  33160. var data = {};
  33161. var newdata = {};
  33162. var kindIndex;
  33163. var kind;
  33164. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33165. kind = kinds[kindIndex];
  33166. var vertexBuffer = this.getVertexBuffer(kind);
  33167. vbs[kind] = vertexBuffer;
  33168. data[kind] = vbs[kind].getData();
  33169. newdata[kind] = [];
  33170. }
  33171. // Save previous submeshes
  33172. var previousSubmeshes = this.subMeshes.slice(0);
  33173. var indices = this.getIndices();
  33174. var totalIndices = this.getTotalIndices();
  33175. // Generating unique vertices per face
  33176. var index;
  33177. for (index = 0; index < totalIndices; index++) {
  33178. var vertexIndex = indices[index];
  33179. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33180. kind = kinds[kindIndex];
  33181. var stride = vbs[kind].getStrideSize();
  33182. for (var offset = 0; offset < stride; offset++) {
  33183. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33184. }
  33185. }
  33186. }
  33187. // Updating indices
  33188. for (index = 0; index < totalIndices; index += 3) {
  33189. indices[index] = index;
  33190. indices[index + 1] = index + 1;
  33191. indices[index + 2] = index + 2;
  33192. }
  33193. this.setIndices(indices);
  33194. // Updating vertex buffers
  33195. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33196. kind = kinds[kindIndex];
  33197. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33198. }
  33199. // Updating submeshes
  33200. this.releaseSubMeshes();
  33201. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33202. var previousOne = previousSubmeshes[submeshIndex];
  33203. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33204. }
  33205. this._unIndexed = true;
  33206. this.synchronizeInstances();
  33207. return this;
  33208. };
  33209. /**
  33210. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33211. * This method returns the Mesh.
  33212. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33213. */
  33214. Mesh.prototype.flipFaces = function (flipNormals) {
  33215. if (flipNormals === void 0) { flipNormals = false; }
  33216. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33217. var i;
  33218. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33219. for (i = 0; i < vertex_data.normals.length; i++) {
  33220. vertex_data.normals[i] *= -1;
  33221. }
  33222. }
  33223. if (vertex_data.indices) {
  33224. var temp;
  33225. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33226. // reassign indices
  33227. temp = vertex_data.indices[i + 1];
  33228. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33229. vertex_data.indices[i + 2] = temp;
  33230. }
  33231. }
  33232. vertex_data.applyToMesh(this);
  33233. return this;
  33234. };
  33235. // Instances
  33236. /**
  33237. * Creates a new InstancedMesh object from the mesh model.
  33238. * An instance shares the same properties and the same material than its model.
  33239. * Only these properties of each instance can then be set individually :
  33240. * - position
  33241. * - rotation
  33242. * - rotationQuaternion
  33243. * - setPivotMatrix
  33244. * - scaling
  33245. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33246. * Warning : this method is not supported for Line mesh and LineSystem
  33247. */
  33248. Mesh.prototype.createInstance = function (name) {
  33249. return new BABYLON.InstancedMesh(name, this);
  33250. };
  33251. /**
  33252. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33253. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33254. * This method returns the Mesh.
  33255. */
  33256. Mesh.prototype.synchronizeInstances = function () {
  33257. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33258. var instance = this.instances[instanceIndex];
  33259. instance._syncSubMeshes();
  33260. }
  33261. return this;
  33262. };
  33263. /**
  33264. * Simplify the mesh according to the given array of settings.
  33265. * Function will return immediately and will simplify async. It returns the Mesh.
  33266. * @param settings a collection of simplification settings.
  33267. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33268. * @param type the type of simplification to run.
  33269. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33270. */
  33271. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33272. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33273. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33274. this.getScene().simplificationQueue.addTask({
  33275. settings: settings,
  33276. parallelProcessing: parallelProcessing,
  33277. mesh: this,
  33278. simplificationType: simplificationType,
  33279. successCallback: successCallback
  33280. });
  33281. return this;
  33282. };
  33283. /**
  33284. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33285. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33286. * This should be used together with the simplification to avoid disappearing triangles.
  33287. * Returns the Mesh.
  33288. * @param successCallback an optional success callback to be called after the optimization finished.
  33289. */
  33290. Mesh.prototype.optimizeIndices = function (successCallback) {
  33291. var _this = this;
  33292. var indices = this.getIndices();
  33293. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33294. if (!positions || !indices) {
  33295. return this;
  33296. }
  33297. var vectorPositions = new Array();
  33298. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33299. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33300. }
  33301. var dupes = new Array();
  33302. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33303. var realPos = vectorPositions.length - 1 - iteration;
  33304. var testedPosition = vectorPositions[realPos];
  33305. for (var j = 0; j < realPos; ++j) {
  33306. var againstPosition = vectorPositions[j];
  33307. if (testedPosition.equals(againstPosition)) {
  33308. dupes[realPos] = j;
  33309. break;
  33310. }
  33311. }
  33312. }, function () {
  33313. for (var i = 0; i < indices.length; ++i) {
  33314. indices[i] = dupes[indices[i]] || indices[i];
  33315. }
  33316. //indices are now reordered
  33317. var originalSubMeshes = _this.subMeshes.slice(0);
  33318. _this.setIndices(indices);
  33319. _this.subMeshes = originalSubMeshes;
  33320. if (successCallback) {
  33321. successCallback(_this);
  33322. }
  33323. });
  33324. return this;
  33325. };
  33326. Mesh.prototype.serialize = function (serializationObject) {
  33327. serializationObject.name = this.name;
  33328. serializationObject.id = this.id;
  33329. serializationObject.type = this.getClassName();
  33330. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33331. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33332. }
  33333. serializationObject.position = this.position.asArray();
  33334. if (this.rotationQuaternion) {
  33335. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33336. }
  33337. else if (this.rotation) {
  33338. serializationObject.rotation = this.rotation.asArray();
  33339. }
  33340. serializationObject.scaling = this.scaling.asArray();
  33341. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33342. serializationObject.isEnabled = this.isEnabled(false);
  33343. serializationObject.isVisible = this.isVisible;
  33344. serializationObject.infiniteDistance = this.infiniteDistance;
  33345. serializationObject.pickable = this.isPickable;
  33346. serializationObject.receiveShadows = this.receiveShadows;
  33347. serializationObject.billboardMode = this.billboardMode;
  33348. serializationObject.visibility = this.visibility;
  33349. serializationObject.checkCollisions = this.checkCollisions;
  33350. serializationObject.isBlocker = this.isBlocker;
  33351. // Parent
  33352. if (this.parent) {
  33353. serializationObject.parentId = this.parent.id;
  33354. }
  33355. // Geometry
  33356. serializationObject.isUnIndexed = this.isUnIndexed;
  33357. var geometry = this._geometry;
  33358. if (geometry) {
  33359. var geometryId = geometry.id;
  33360. serializationObject.geometryId = geometryId;
  33361. // SubMeshes
  33362. serializationObject.subMeshes = [];
  33363. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33364. var subMesh = this.subMeshes[subIndex];
  33365. serializationObject.subMeshes.push({
  33366. materialIndex: subMesh.materialIndex,
  33367. verticesStart: subMesh.verticesStart,
  33368. verticesCount: subMesh.verticesCount,
  33369. indexStart: subMesh.indexStart,
  33370. indexCount: subMesh.indexCount
  33371. });
  33372. }
  33373. }
  33374. // Material
  33375. if (this.material) {
  33376. serializationObject.materialId = this.material.id;
  33377. }
  33378. else {
  33379. this.material = null;
  33380. }
  33381. // Morph targets
  33382. if (this.morphTargetManager) {
  33383. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33384. }
  33385. // Skeleton
  33386. if (this.skeleton) {
  33387. serializationObject.skeletonId = this.skeleton.id;
  33388. }
  33389. // Physics
  33390. //TODO implement correct serialization for physics impostors.
  33391. var impostor = this.getPhysicsImpostor();
  33392. if (impostor) {
  33393. serializationObject.physicsMass = impostor.getParam("mass");
  33394. serializationObject.physicsFriction = impostor.getParam("friction");
  33395. serializationObject.physicsRestitution = impostor.getParam("mass");
  33396. serializationObject.physicsImpostor = impostor.type;
  33397. }
  33398. // Metadata
  33399. if (this.metadata) {
  33400. serializationObject.metadata = this.metadata;
  33401. }
  33402. // Instances
  33403. serializationObject.instances = [];
  33404. for (var index = 0; index < this.instances.length; index++) {
  33405. var instance = this.instances[index];
  33406. var serializationInstance = {
  33407. name: instance.name,
  33408. id: instance.id,
  33409. position: instance.position.asArray(),
  33410. scaling: instance.scaling.asArray()
  33411. };
  33412. if (instance.rotationQuaternion) {
  33413. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33414. }
  33415. else if (instance.rotation) {
  33416. serializationInstance.rotation = instance.rotation.asArray();
  33417. }
  33418. serializationObject.instances.push(serializationInstance);
  33419. // Animations
  33420. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33421. serializationInstance.ranges = instance.serializeAnimationRanges();
  33422. }
  33423. //
  33424. // Animations
  33425. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33426. serializationObject.ranges = this.serializeAnimationRanges();
  33427. // Layer mask
  33428. serializationObject.layerMask = this.layerMask;
  33429. // Alpha
  33430. serializationObject.alphaIndex = this.alphaIndex;
  33431. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33432. // Overlay
  33433. serializationObject.overlayAlpha = this.overlayAlpha;
  33434. serializationObject.overlayColor = this.overlayColor.asArray();
  33435. serializationObject.renderOverlay = this.renderOverlay;
  33436. // Fog
  33437. serializationObject.applyFog = this.applyFog;
  33438. // Action Manager
  33439. if (this.actionManager) {
  33440. serializationObject.actions = this.actionManager.serialize(this.name);
  33441. }
  33442. };
  33443. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33444. if (!this.geometry) {
  33445. return;
  33446. }
  33447. this._markSubMeshesAsAttributesDirty();
  33448. var morphTargetManager = this._morphTargetManager;
  33449. if (morphTargetManager && morphTargetManager.vertexCount) {
  33450. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33451. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33452. this.morphTargetManager = null;
  33453. return;
  33454. }
  33455. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33456. var morphTarget = morphTargetManager.getActiveTarget(index);
  33457. var positions = morphTarget.getPositions();
  33458. if (!positions) {
  33459. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33460. return;
  33461. }
  33462. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33463. var normals = morphTarget.getNormals();
  33464. if (normals) {
  33465. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33466. }
  33467. var tangents = morphTarget.getTangents();
  33468. if (tangents) {
  33469. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33470. }
  33471. }
  33472. }
  33473. else {
  33474. var index = 0;
  33475. // Positions
  33476. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33477. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33478. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33479. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33480. }
  33481. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33482. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33483. }
  33484. index++;
  33485. }
  33486. }
  33487. };
  33488. // Statics
  33489. /**
  33490. * Returns a new Mesh object parsed from the source provided.
  33491. * The parameter `parsedMesh` is the source.
  33492. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33493. */
  33494. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33495. var mesh;
  33496. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33497. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33498. }
  33499. else {
  33500. mesh = new Mesh(parsedMesh.name, scene);
  33501. }
  33502. mesh.id = parsedMesh.id;
  33503. if (BABYLON.Tags) {
  33504. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33505. }
  33506. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33507. if (parsedMesh.metadata !== undefined) {
  33508. mesh.metadata = parsedMesh.metadata;
  33509. }
  33510. if (parsedMesh.rotationQuaternion) {
  33511. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33512. }
  33513. else if (parsedMesh.rotation) {
  33514. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33515. }
  33516. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33517. if (parsedMesh.localMatrix) {
  33518. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33519. }
  33520. else if (parsedMesh.pivotMatrix) {
  33521. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33522. }
  33523. mesh.setEnabled(parsedMesh.isEnabled);
  33524. mesh.isVisible = parsedMesh.isVisible;
  33525. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33526. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33527. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33528. if (parsedMesh.applyFog !== undefined) {
  33529. mesh.applyFog = parsedMesh.applyFog;
  33530. }
  33531. if (parsedMesh.pickable !== undefined) {
  33532. mesh.isPickable = parsedMesh.pickable;
  33533. }
  33534. if (parsedMesh.alphaIndex !== undefined) {
  33535. mesh.alphaIndex = parsedMesh.alphaIndex;
  33536. }
  33537. mesh.receiveShadows = parsedMesh.receiveShadows;
  33538. mesh.billboardMode = parsedMesh.billboardMode;
  33539. if (parsedMesh.visibility !== undefined) {
  33540. mesh.visibility = parsedMesh.visibility;
  33541. }
  33542. mesh.checkCollisions = parsedMesh.checkCollisions;
  33543. if (parsedMesh.isBlocker !== undefined) {
  33544. mesh.isBlocker = parsedMesh.isBlocker;
  33545. }
  33546. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33547. // freezeWorldMatrix
  33548. if (parsedMesh.freezeWorldMatrix) {
  33549. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33550. }
  33551. // Parent
  33552. if (parsedMesh.parentId) {
  33553. mesh._waitingParentId = parsedMesh.parentId;
  33554. }
  33555. // Actions
  33556. if (parsedMesh.actions !== undefined) {
  33557. mesh._waitingActions = parsedMesh.actions;
  33558. }
  33559. // Overlay
  33560. if (parsedMesh.overlayAlpha !== undefined) {
  33561. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33562. }
  33563. if (parsedMesh.overlayColor !== undefined) {
  33564. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33565. }
  33566. if (parsedMesh.renderOverlay !== undefined) {
  33567. mesh.renderOverlay = parsedMesh.renderOverlay;
  33568. }
  33569. // Geometry
  33570. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33571. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33572. if (parsedMesh.delayLoadingFile) {
  33573. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33574. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33575. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33576. if (parsedMesh._binaryInfo) {
  33577. mesh._binaryInfo = parsedMesh._binaryInfo;
  33578. }
  33579. mesh._delayInfo = [];
  33580. if (parsedMesh.hasUVs) {
  33581. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33582. }
  33583. if (parsedMesh.hasUVs2) {
  33584. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33585. }
  33586. if (parsedMesh.hasUVs3) {
  33587. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33588. }
  33589. if (parsedMesh.hasUVs4) {
  33590. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33591. }
  33592. if (parsedMesh.hasUVs5) {
  33593. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33594. }
  33595. if (parsedMesh.hasUVs6) {
  33596. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33597. }
  33598. if (parsedMesh.hasColors) {
  33599. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33600. }
  33601. if (parsedMesh.hasMatricesIndices) {
  33602. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33603. }
  33604. if (parsedMesh.hasMatricesWeights) {
  33605. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33606. }
  33607. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33608. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33609. mesh._checkDelayState();
  33610. }
  33611. }
  33612. else {
  33613. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33614. }
  33615. // Material
  33616. if (parsedMesh.materialId) {
  33617. mesh.setMaterialByID(parsedMesh.materialId);
  33618. }
  33619. else {
  33620. mesh.material = null;
  33621. }
  33622. // Morph targets
  33623. if (parsedMesh.morphTargetManagerId > -1) {
  33624. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33625. }
  33626. // Skeleton
  33627. if (parsedMesh.skeletonId > -1) {
  33628. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33629. if (parsedMesh.numBoneInfluencers) {
  33630. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33631. }
  33632. }
  33633. // Animations
  33634. if (parsedMesh.animations) {
  33635. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33636. var parsedAnimation = parsedMesh.animations[animationIndex];
  33637. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33638. }
  33639. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33640. }
  33641. if (parsedMesh.autoAnimate) {
  33642. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33643. }
  33644. // Layer Mask
  33645. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33646. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33647. }
  33648. else {
  33649. mesh.layerMask = 0x0FFFFFFF;
  33650. }
  33651. // Physics
  33652. if (parsedMesh.physicsImpostor) {
  33653. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33654. mass: parsedMesh.physicsMass,
  33655. friction: parsedMesh.physicsFriction,
  33656. restitution: parsedMesh.physicsRestitution
  33657. }, scene);
  33658. }
  33659. // Instances
  33660. if (parsedMesh.instances) {
  33661. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33662. var parsedInstance = parsedMesh.instances[index];
  33663. var instance = mesh.createInstance(parsedInstance.name);
  33664. if (parsedInstance.id) {
  33665. instance.id = parsedInstance.id;
  33666. }
  33667. if (BABYLON.Tags) {
  33668. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33669. }
  33670. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33671. if (parsedInstance.parentId) {
  33672. instance._waitingParentId = parsedInstance.parentId;
  33673. }
  33674. if (parsedInstance.rotationQuaternion) {
  33675. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33676. }
  33677. else if (parsedInstance.rotation) {
  33678. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33679. }
  33680. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33681. instance.checkCollisions = mesh.checkCollisions;
  33682. if (parsedMesh.animations) {
  33683. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33684. parsedAnimation = parsedMesh.animations[animationIndex];
  33685. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33686. }
  33687. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33688. if (parsedMesh.autoAnimate) {
  33689. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33690. }
  33691. }
  33692. }
  33693. }
  33694. return mesh;
  33695. };
  33696. /**
  33697. * Creates a ribbon mesh.
  33698. * Please consider using the same method from the MeshBuilder class instead.
  33699. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33700. *
  33701. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33702. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33703. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33704. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33705. * 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.
  33706. * 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.
  33707. * 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
  33708. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33709. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33711. */
  33712. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33713. if (closeArray === void 0) { closeArray = false; }
  33714. if (updatable === void 0) { updatable = false; }
  33715. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33716. pathArray: pathArray,
  33717. closeArray: closeArray,
  33718. closePath: closePath,
  33719. offset: offset,
  33720. updatable: updatable,
  33721. sideOrientation: sideOrientation,
  33722. instance: instance
  33723. }, scene);
  33724. };
  33725. /**
  33726. * Creates a plane polygonal mesh. By default, this is a disc.
  33727. * Please consider using the same method from the MeshBuilder class instead.
  33728. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33729. * 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.
  33730. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33731. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33732. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33733. */
  33734. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33735. if (scene === void 0) { scene = null; }
  33736. var options = {
  33737. radius: radius,
  33738. tessellation: tessellation,
  33739. sideOrientation: sideOrientation,
  33740. updatable: updatable
  33741. };
  33742. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33743. };
  33744. /**
  33745. * Creates a box mesh.
  33746. * Please consider using the same method from the MeshBuilder class instead.
  33747. * The parameter `size` sets the size (float) of each box side (default 1).
  33748. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33749. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33750. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33751. */
  33752. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33753. if (scene === void 0) { scene = null; }
  33754. var options = {
  33755. size: size,
  33756. sideOrientation: sideOrientation,
  33757. updatable: updatable
  33758. };
  33759. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33760. };
  33761. /**
  33762. * Creates a sphere mesh.
  33763. * Please consider using the same method from the MeshBuilder class instead.
  33764. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33765. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33767. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33769. */
  33770. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33771. var options = {
  33772. segments: segments,
  33773. diameterX: diameter,
  33774. diameterY: diameter,
  33775. diameterZ: diameter,
  33776. sideOrientation: sideOrientation,
  33777. updatable: updatable
  33778. };
  33779. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33780. };
  33781. /**
  33782. * Creates a cylinder or a cone mesh.
  33783. * Please consider using the same method from the MeshBuilder class instead.
  33784. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33785. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33786. * 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.
  33787. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33788. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33789. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33790. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33791. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33792. */
  33793. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33794. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33795. if (scene !== undefined) {
  33796. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33797. updatable = scene;
  33798. }
  33799. scene = subdivisions;
  33800. subdivisions = 1;
  33801. }
  33802. var options = {
  33803. height: height,
  33804. diameterTop: diameterTop,
  33805. diameterBottom: diameterBottom,
  33806. tessellation: tessellation,
  33807. subdivisions: subdivisions,
  33808. sideOrientation: sideOrientation,
  33809. updatable: updatable
  33810. };
  33811. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33812. };
  33813. // Torus (Code from SharpDX.org)
  33814. /**
  33815. * Creates a torus mesh.
  33816. * Please consider using the same method from the MeshBuilder class instead.
  33817. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33818. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33819. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33820. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33821. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33822. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33823. */
  33824. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33825. var options = {
  33826. diameter: diameter,
  33827. thickness: thickness,
  33828. tessellation: tessellation,
  33829. sideOrientation: sideOrientation,
  33830. updatable: updatable
  33831. };
  33832. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33833. };
  33834. /**
  33835. * Creates a torus knot mesh.
  33836. * Please consider using the same method from the MeshBuilder class instead.
  33837. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33838. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33839. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33840. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33842. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33844. */
  33845. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33846. var options = {
  33847. radius: radius,
  33848. tube: tube,
  33849. radialSegments: radialSegments,
  33850. tubularSegments: tubularSegments,
  33851. p: p,
  33852. q: q,
  33853. sideOrientation: sideOrientation,
  33854. updatable: updatable
  33855. };
  33856. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33857. };
  33858. /**
  33859. * Creates a line mesh.
  33860. * Please consider using the same method from the MeshBuilder class instead.
  33861. * 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.
  33862. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33863. * The parameter `points` is an array successive Vector3.
  33864. * 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
  33865. * When updating an instance, remember that only point positions can change, not the number of points.
  33866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33867. */
  33868. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33869. if (scene === void 0) { scene = null; }
  33870. if (updatable === void 0) { updatable = false; }
  33871. if (instance === void 0) { instance = null; }
  33872. var options = {
  33873. points: points,
  33874. updatable: updatable,
  33875. instance: instance
  33876. };
  33877. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33878. };
  33879. /**
  33880. * Creates a dashed line mesh.
  33881. * Please consider using the same method from the MeshBuilder class instead.
  33882. * 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.
  33883. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33884. * The parameter `points` is an array successive Vector3.
  33885. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33886. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33887. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33888. * 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
  33889. * When updating an instance, remember that only point positions can change, not the number of points.
  33890. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33891. */
  33892. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33893. if (scene === void 0) { scene = null; }
  33894. var options = {
  33895. points: points,
  33896. dashSize: dashSize,
  33897. gapSize: gapSize,
  33898. dashNb: dashNb,
  33899. updatable: updatable,
  33900. instance: instance
  33901. };
  33902. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33903. };
  33904. /**
  33905. * Creates a polygon mesh.
  33906. * Please consider using the same method from the MeshBuilder class instead.
  33907. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33908. * 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.
  33909. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33911. * Remember you can only change the shape positions, not their number when updating a polygon.
  33912. */
  33913. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33914. var options = {
  33915. shape: shape,
  33916. holes: holes,
  33917. updatable: updatable,
  33918. sideOrientation: sideOrientation
  33919. };
  33920. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33921. };
  33922. /**
  33923. * Creates an extruded polygon mesh, with depth in the Y direction.
  33924. * Please consider using the same method from the MeshBuilder class instead.
  33925. */
  33926. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33927. var options = {
  33928. shape: shape,
  33929. holes: holes,
  33930. depth: depth,
  33931. updatable: updatable,
  33932. sideOrientation: sideOrientation
  33933. };
  33934. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33935. };
  33936. /**
  33937. * Creates an extruded shape mesh.
  33938. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33939. * Please consider using the same method from the MeshBuilder class instead.
  33940. *
  33941. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33942. * 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
  33943. * extruded along the Z axis.
  33944. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33945. * 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.
  33946. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33947. * 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
  33948. * 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
  33949. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33950. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33951. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33952. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33953. */
  33954. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33955. if (scene === void 0) { scene = null; }
  33956. var options = {
  33957. shape: shape,
  33958. path: path,
  33959. scale: scale,
  33960. rotation: rotation,
  33961. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33962. sideOrientation: sideOrientation,
  33963. instance: instance,
  33964. updatable: updatable
  33965. };
  33966. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33967. };
  33968. /**
  33969. * Creates an custom extruded shape mesh.
  33970. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  33971. * Please consider using the same method from the MeshBuilder class instead.
  33972. *
  33973. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33974. * 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
  33975. * extruded along the Z axis.
  33976. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33977. * 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
  33978. * and the distance of this point from the begining of the path :
  33979. * ```javascript
  33980. * var rotationFunction = function(i, distance) {
  33981. * // do things
  33982. * return rotationValue; }
  33983. * ```
  33984. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33985. * 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
  33986. * and the distance of this point from the begining of the path :
  33987. * ```javascript
  33988. * var scaleFunction = function(i, distance) {
  33989. * // do things
  33990. * return scaleValue;}
  33991. * ```
  33992. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33993. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33994. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33995. * 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
  33996. * 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
  33997. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33998. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33999. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34000. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34001. */
  34002. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34003. var options = {
  34004. shape: shape,
  34005. path: path,
  34006. scaleFunction: scaleFunction,
  34007. rotationFunction: rotationFunction,
  34008. ribbonCloseArray: ribbonCloseArray,
  34009. ribbonClosePath: ribbonClosePath,
  34010. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34011. sideOrientation: sideOrientation,
  34012. instance: instance,
  34013. updatable: updatable
  34014. };
  34015. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34016. };
  34017. /**
  34018. * Creates lathe mesh.
  34019. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34020. * Please consider using the same method from the MeshBuilder class instead.
  34021. * 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
  34022. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34023. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34024. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34025. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34026. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34028. */
  34029. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34030. var options = {
  34031. shape: shape,
  34032. radius: radius,
  34033. tessellation: tessellation,
  34034. sideOrientation: sideOrientation,
  34035. updatable: updatable
  34036. };
  34037. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34038. };
  34039. /**
  34040. * Creates a plane mesh.
  34041. * Please consider using the same method from the MeshBuilder class instead.
  34042. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34044. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34046. */
  34047. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34048. var options = {
  34049. size: size,
  34050. width: size,
  34051. height: size,
  34052. sideOrientation: sideOrientation,
  34053. updatable: updatable
  34054. };
  34055. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34056. };
  34057. /**
  34058. * Creates a ground mesh.
  34059. * Please consider using the same method from the MeshBuilder class instead.
  34060. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34061. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34062. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34063. */
  34064. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34065. var options = {
  34066. width: width,
  34067. height: height,
  34068. subdivisions: subdivisions,
  34069. updatable: updatable
  34070. };
  34071. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34072. };
  34073. /**
  34074. * Creates a tiled ground mesh.
  34075. * Please consider using the same method from the MeshBuilder class instead.
  34076. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34077. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34078. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34079. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34080. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34081. * numbers of subdivisions on the ground width and height of each tile.
  34082. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34083. */
  34084. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34085. var options = {
  34086. xmin: xmin,
  34087. zmin: zmin,
  34088. xmax: xmax,
  34089. zmax: zmax,
  34090. subdivisions: subdivisions,
  34091. precision: precision,
  34092. updatable: updatable
  34093. };
  34094. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34095. };
  34096. /**
  34097. * Creates a ground mesh from a height map.
  34098. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34099. * Please consider using the same method from the MeshBuilder class instead.
  34100. * The parameter `url` sets the URL of the height map image resource.
  34101. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34102. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34103. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34104. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34105. * 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).
  34106. * This function is passed the newly built mesh :
  34107. * ```javascript
  34108. * function(mesh) { // do things
  34109. * return; }
  34110. * ```
  34111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34112. */
  34113. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34114. var options = {
  34115. width: width,
  34116. height: height,
  34117. subdivisions: subdivisions,
  34118. minHeight: minHeight,
  34119. maxHeight: maxHeight,
  34120. updatable: updatable,
  34121. onReady: onReady
  34122. };
  34123. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34124. };
  34125. /**
  34126. * Creates a tube mesh.
  34127. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  34128. * Please consider using the same method from the MeshBuilder class instead.
  34129. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34130. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34131. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34132. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34133. * 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.
  34134. * It must return a radius value (positive float) :
  34135. * ```javascript
  34136. * var radiusFunction = function(i, distance) {
  34137. * // do things
  34138. * return radius; }
  34139. * ```
  34140. * 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
  34141. * 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
  34142. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34143. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34144. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34145. */
  34146. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34147. var options = {
  34148. path: path,
  34149. radius: radius,
  34150. tessellation: tessellation,
  34151. radiusFunction: radiusFunction,
  34152. arc: 1,
  34153. cap: cap,
  34154. updatable: updatable,
  34155. sideOrientation: sideOrientation,
  34156. instance: instance
  34157. };
  34158. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34159. };
  34160. /**
  34161. * Creates a polyhedron mesh.
  34162. * Please consider using the same method from the MeshBuilder class instead.
  34163. * 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
  34164. * to choose the wanted type.
  34165. * The parameter `size` (positive float, default 1) sets the polygon size.
  34166. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34167. * 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`.
  34168. * 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
  34169. * 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)`).
  34170. * 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
  34171. * 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.
  34172. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34173. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34175. */
  34176. Mesh.CreatePolyhedron = function (name, options, scene) {
  34177. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34178. };
  34179. /**
  34180. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34181. * Please consider using the same method from the MeshBuilder class instead.
  34182. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34183. * 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`).
  34184. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34185. * 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.
  34186. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34187. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34188. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34189. */
  34190. Mesh.CreateIcoSphere = function (name, options, scene) {
  34191. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34192. };
  34193. /**
  34194. * Creates a decal mesh.
  34195. * Please consider using the same method from the MeshBuilder class instead.
  34196. * 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.
  34197. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34198. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34199. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34200. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34201. */
  34202. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34203. var options = {
  34204. position: position,
  34205. normal: normal,
  34206. size: size,
  34207. angle: angle
  34208. };
  34209. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34210. };
  34211. // Skeletons
  34212. /**
  34213. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34214. */
  34215. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34216. if (!this._sourcePositions) {
  34217. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34218. if (!source) {
  34219. return this._sourcePositions;
  34220. }
  34221. this._sourcePositions = new Float32Array(source);
  34222. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34223. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34224. }
  34225. }
  34226. return this._sourcePositions;
  34227. };
  34228. /**
  34229. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34230. */
  34231. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34232. if (!this._sourceNormals) {
  34233. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34234. if (!source) {
  34235. return this._sourceNormals;
  34236. }
  34237. this._sourceNormals = new Float32Array(source);
  34238. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34239. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34240. }
  34241. }
  34242. return this._sourceNormals;
  34243. };
  34244. /**
  34245. * Updates the vertex buffer by applying transformation from the bones.
  34246. * Returns the Mesh.
  34247. *
  34248. * @param {skeleton} skeleton to apply
  34249. */
  34250. Mesh.prototype.applySkeleton = function (skeleton) {
  34251. if (!this.geometry) {
  34252. return this;
  34253. }
  34254. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34255. return this;
  34256. }
  34257. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34258. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34259. return this;
  34260. }
  34261. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34262. return this;
  34263. }
  34264. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34265. return this;
  34266. }
  34267. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34268. return this;
  34269. }
  34270. if (!this._sourcePositions) {
  34271. var submeshes = this.subMeshes.slice();
  34272. this.setPositionsForCPUSkinning();
  34273. this.subMeshes = submeshes;
  34274. }
  34275. if (!this._sourceNormals) {
  34276. this.setNormalsForCPUSkinning();
  34277. }
  34278. // positionsData checks for not being Float32Array will only pass at most once
  34279. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34280. if (!positionsData) {
  34281. return this;
  34282. }
  34283. if (!(positionsData instanceof Float32Array)) {
  34284. positionsData = new Float32Array(positionsData);
  34285. }
  34286. // normalsData checks for not being Float32Array will only pass at most once
  34287. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34288. if (!normalsData) {
  34289. return this;
  34290. }
  34291. if (!(normalsData instanceof Float32Array)) {
  34292. normalsData = new Float32Array(normalsData);
  34293. }
  34294. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34295. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34296. if (!matricesWeightsData || !matricesIndicesData) {
  34297. return this;
  34298. }
  34299. var needExtras = this.numBoneInfluencers > 4;
  34300. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34301. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34302. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34303. var tempVector3 = BABYLON.Vector3.Zero();
  34304. var finalMatrix = new BABYLON.Matrix();
  34305. var tempMatrix = new BABYLON.Matrix();
  34306. var matWeightIdx = 0;
  34307. var inf;
  34308. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34309. var weight;
  34310. for (inf = 0; inf < 4; inf++) {
  34311. weight = matricesWeightsData[matWeightIdx + inf];
  34312. if (weight > 0) {
  34313. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34314. finalMatrix.addToSelf(tempMatrix);
  34315. }
  34316. else
  34317. break;
  34318. }
  34319. if (needExtras) {
  34320. for (inf = 0; inf < 4; inf++) {
  34321. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34322. if (weight > 0) {
  34323. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34324. finalMatrix.addToSelf(tempMatrix);
  34325. }
  34326. else
  34327. break;
  34328. }
  34329. }
  34330. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34331. tempVector3.toArray(positionsData, index);
  34332. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34333. tempVector3.toArray(normalsData, index);
  34334. finalMatrix.reset();
  34335. }
  34336. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34337. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34338. return this;
  34339. };
  34340. // Tools
  34341. /**
  34342. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34343. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34344. */
  34345. Mesh.MinMax = function (meshes) {
  34346. var minVector = null;
  34347. var maxVector = null;
  34348. meshes.forEach(function (mesh, index, array) {
  34349. var boundingInfo = mesh.getBoundingInfo();
  34350. var boundingBox = boundingInfo.boundingBox;
  34351. if (!minVector || !maxVector) {
  34352. minVector = boundingBox.minimumWorld;
  34353. maxVector = boundingBox.maximumWorld;
  34354. }
  34355. else {
  34356. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34357. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34358. }
  34359. });
  34360. if (!minVector || !maxVector) {
  34361. return {
  34362. min: BABYLON.Vector3.Zero(),
  34363. max: BABYLON.Vector3.Zero()
  34364. };
  34365. }
  34366. return {
  34367. min: minVector,
  34368. max: maxVector
  34369. };
  34370. };
  34371. /**
  34372. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34373. */
  34374. Mesh.Center = function (meshesOrMinMaxVector) {
  34375. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34376. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34377. };
  34378. /**
  34379. * Merge the array of meshes into a single mesh for performance reasons.
  34380. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34381. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34382. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34383. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34384. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34385. */
  34386. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34387. if (disposeSource === void 0) { disposeSource = true; }
  34388. var index;
  34389. if (!allow32BitsIndices) {
  34390. var totalVertices = 0;
  34391. // Counting vertices
  34392. for (index = 0; index < meshes.length; index++) {
  34393. if (meshes[index]) {
  34394. totalVertices += meshes[index].getTotalVertices();
  34395. if (totalVertices > 65536) {
  34396. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34397. return null;
  34398. }
  34399. }
  34400. }
  34401. }
  34402. // Merge
  34403. var vertexData = null;
  34404. var otherVertexData;
  34405. var indiceArray = new Array();
  34406. var source = null;
  34407. for (index = 0; index < meshes.length; index++) {
  34408. if (meshes[index]) {
  34409. meshes[index].computeWorldMatrix(true);
  34410. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34411. otherVertexData.transform(meshes[index].getWorldMatrix());
  34412. if (vertexData) {
  34413. vertexData.merge(otherVertexData);
  34414. }
  34415. else {
  34416. vertexData = otherVertexData;
  34417. source = meshes[index];
  34418. }
  34419. if (subdivideWithSubMeshes) {
  34420. indiceArray.push(meshes[index].getTotalIndices());
  34421. }
  34422. }
  34423. }
  34424. source = source;
  34425. if (!meshSubclass) {
  34426. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34427. }
  34428. vertexData.applyToMesh(meshSubclass);
  34429. // Setting properties
  34430. meshSubclass.material = source.material;
  34431. meshSubclass.checkCollisions = source.checkCollisions;
  34432. // Cleaning
  34433. if (disposeSource) {
  34434. for (index = 0; index < meshes.length; index++) {
  34435. if (meshes[index]) {
  34436. meshes[index].dispose();
  34437. }
  34438. }
  34439. }
  34440. // Subdivide
  34441. if (subdivideWithSubMeshes) {
  34442. //-- removal of global submesh
  34443. meshSubclass.releaseSubMeshes();
  34444. index = 0;
  34445. var offset = 0;
  34446. //-- apply subdivision according to index table
  34447. while (index < indiceArray.length) {
  34448. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34449. offset += indiceArray[index];
  34450. index++;
  34451. }
  34452. }
  34453. return meshSubclass;
  34454. };
  34455. // Consts
  34456. Mesh._FRONTSIDE = 0;
  34457. Mesh._BACKSIDE = 1;
  34458. Mesh._DOUBLESIDE = 2;
  34459. Mesh._DEFAULTSIDE = 0;
  34460. Mesh._NO_CAP = 0;
  34461. Mesh._CAP_START = 1;
  34462. Mesh._CAP_END = 2;
  34463. Mesh._CAP_ALL = 3;
  34464. return Mesh;
  34465. }(BABYLON.AbstractMesh));
  34466. BABYLON.Mesh = Mesh;
  34467. })(BABYLON || (BABYLON = {}));
  34468. //# sourceMappingURL=babylon.mesh.js.map
  34469. var BABYLON;
  34470. (function (BABYLON) {
  34471. var BaseSubMesh = /** @class */ (function () {
  34472. function BaseSubMesh() {
  34473. }
  34474. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34475. get: function () {
  34476. return this._materialEffect;
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34482. if (defines === void 0) { defines = null; }
  34483. if (this._materialEffect === effect) {
  34484. if (!effect) {
  34485. this._materialDefines = null;
  34486. }
  34487. return;
  34488. }
  34489. this._materialDefines = defines;
  34490. this._materialEffect = effect;
  34491. };
  34492. return BaseSubMesh;
  34493. }());
  34494. BABYLON.BaseSubMesh = BaseSubMesh;
  34495. var SubMesh = /** @class */ (function (_super) {
  34496. __extends(SubMesh, _super);
  34497. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34498. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34499. var _this = _super.call(this) || this;
  34500. _this.materialIndex = materialIndex;
  34501. _this.verticesStart = verticesStart;
  34502. _this.verticesCount = verticesCount;
  34503. _this.indexStart = indexStart;
  34504. _this.indexCount = indexCount;
  34505. _this._renderId = 0;
  34506. _this._mesh = mesh;
  34507. _this._renderingMesh = renderingMesh || mesh;
  34508. mesh.subMeshes.push(_this);
  34509. _this._trianglePlanes = [];
  34510. _this._id = mesh.subMeshes.length - 1;
  34511. if (createBoundingBox) {
  34512. _this.refreshBoundingInfo();
  34513. mesh.computeWorldMatrix(true);
  34514. }
  34515. return _this;
  34516. }
  34517. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34518. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34519. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34520. };
  34521. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34522. get: function () {
  34523. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34524. },
  34525. enumerable: true,
  34526. configurable: true
  34527. });
  34528. /**
  34529. * Returns the submesh BoudingInfo object.
  34530. */
  34531. SubMesh.prototype.getBoundingInfo = function () {
  34532. if (this.IsGlobal) {
  34533. return this._mesh.getBoundingInfo();
  34534. }
  34535. return this._boundingInfo;
  34536. };
  34537. /**
  34538. * Sets the submesh BoundingInfo.
  34539. * Return the SubMesh.
  34540. */
  34541. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34542. this._boundingInfo = boundingInfo;
  34543. return this;
  34544. };
  34545. /**
  34546. * Returns the mesh of the current submesh.
  34547. */
  34548. SubMesh.prototype.getMesh = function () {
  34549. return this._mesh;
  34550. };
  34551. /**
  34552. * Returns the rendering mesh of the submesh.
  34553. */
  34554. SubMesh.prototype.getRenderingMesh = function () {
  34555. return this._renderingMesh;
  34556. };
  34557. /**
  34558. * Returns the submesh material.
  34559. */
  34560. SubMesh.prototype.getMaterial = function () {
  34561. var rootMaterial = this._renderingMesh.material;
  34562. if (rootMaterial === null || rootMaterial === undefined) {
  34563. return this._mesh.getScene().defaultMaterial;
  34564. }
  34565. else if (rootMaterial.getSubMaterial) {
  34566. var multiMaterial = rootMaterial;
  34567. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34568. if (this._currentMaterial !== effectiveMaterial) {
  34569. this._currentMaterial = effectiveMaterial;
  34570. this._materialDefines = null;
  34571. }
  34572. return effectiveMaterial;
  34573. }
  34574. return rootMaterial;
  34575. };
  34576. // Methods
  34577. /**
  34578. * Sets a new updated BoundingInfo object to the submesh.
  34579. * Returns the SubMesh.
  34580. */
  34581. SubMesh.prototype.refreshBoundingInfo = function () {
  34582. this._lastColliderWorldVertices = null;
  34583. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34584. return this;
  34585. }
  34586. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34587. if (!data) {
  34588. this._boundingInfo = this._mesh.getBoundingInfo();
  34589. return this;
  34590. }
  34591. var indices = this._renderingMesh.getIndices();
  34592. var extend;
  34593. //is this the only submesh?
  34594. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34595. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34596. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34597. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34598. }
  34599. else {
  34600. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34601. }
  34602. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34603. return this;
  34604. };
  34605. SubMesh.prototype._checkCollision = function (collider) {
  34606. var boundingInfo = this.getBoundingInfo();
  34607. return boundingInfo._checkCollision(collider);
  34608. };
  34609. /**
  34610. * Updates the submesh BoundingInfo.
  34611. * Returns the Submesh.
  34612. */
  34613. SubMesh.prototype.updateBoundingInfo = function (world) {
  34614. var boundingInfo = this.getBoundingInfo();
  34615. if (!boundingInfo) {
  34616. this.refreshBoundingInfo();
  34617. boundingInfo = this.getBoundingInfo();
  34618. }
  34619. boundingInfo.update(world);
  34620. return this;
  34621. };
  34622. /**
  34623. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34624. * Boolean returned.
  34625. */
  34626. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34627. var boundingInfo = this.getBoundingInfo();
  34628. if (!boundingInfo) {
  34629. return false;
  34630. }
  34631. return boundingInfo.isInFrustum(frustumPlanes);
  34632. };
  34633. /**
  34634. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34635. * Boolean returned.
  34636. */
  34637. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34638. var boundingInfo = this.getBoundingInfo();
  34639. if (!boundingInfo) {
  34640. return false;
  34641. }
  34642. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34643. };
  34644. /**
  34645. * Renders the submesh.
  34646. * Returns it.
  34647. */
  34648. SubMesh.prototype.render = function (enableAlphaMode) {
  34649. this._renderingMesh.render(this, enableAlphaMode);
  34650. return this;
  34651. };
  34652. /**
  34653. * Returns a new Index Buffer.
  34654. * Type returned : WebGLBuffer.
  34655. */
  34656. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34657. if (!this._linesIndexBuffer) {
  34658. var linesIndices = [];
  34659. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34660. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34661. }
  34662. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34663. this.linesIndexCount = linesIndices.length;
  34664. }
  34665. return this._linesIndexBuffer;
  34666. };
  34667. /**
  34668. * True is the passed Ray intersects the submesh bounding box.
  34669. * Boolean returned.
  34670. */
  34671. SubMesh.prototype.canIntersects = function (ray) {
  34672. var boundingInfo = this.getBoundingInfo();
  34673. if (!boundingInfo) {
  34674. return false;
  34675. }
  34676. return ray.intersectsBox(boundingInfo.boundingBox);
  34677. };
  34678. /**
  34679. * Returns an object IntersectionInfo.
  34680. */
  34681. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34682. var intersectInfo = null;
  34683. var material = this.getMaterial();
  34684. if (!material) {
  34685. return null;
  34686. }
  34687. switch (material.fillMode) {
  34688. case BABYLON.Material.PointListDrawMode:
  34689. case BABYLON.Material.LineListDrawMode:
  34690. case BABYLON.Material.LineLoopDrawMode:
  34691. case BABYLON.Material.LineStripDrawMode:
  34692. case BABYLON.Material.TriangleFanDrawMode:
  34693. case BABYLON.Material.TriangleStripDrawMode:
  34694. return null;
  34695. }
  34696. // LineMesh first as it's also a Mesh...
  34697. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34698. var lineMesh = this._mesh;
  34699. // Line test
  34700. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34701. var p0 = positions[indices[index]];
  34702. var p1 = positions[indices[index + 1]];
  34703. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34704. if (length < 0) {
  34705. continue;
  34706. }
  34707. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34708. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34709. if (fastCheck) {
  34710. break;
  34711. }
  34712. }
  34713. }
  34714. }
  34715. else {
  34716. // Triangles test
  34717. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34718. var p0 = positions[indices[index]];
  34719. var p1 = positions[indices[index + 1]];
  34720. var p2 = positions[indices[index + 2]];
  34721. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34722. if (currentIntersectInfo) {
  34723. if (currentIntersectInfo.distance < 0) {
  34724. continue;
  34725. }
  34726. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34727. intersectInfo = currentIntersectInfo;
  34728. intersectInfo.faceId = index / 3;
  34729. if (fastCheck) {
  34730. break;
  34731. }
  34732. }
  34733. }
  34734. }
  34735. }
  34736. return intersectInfo;
  34737. };
  34738. SubMesh.prototype._rebuild = function () {
  34739. if (this._linesIndexBuffer) {
  34740. this._linesIndexBuffer = null;
  34741. }
  34742. };
  34743. // Clone
  34744. /**
  34745. * Creates a new Submesh from the passed Mesh.
  34746. */
  34747. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34748. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34749. if (!this.IsGlobal) {
  34750. var boundingInfo = this.getBoundingInfo();
  34751. if (!boundingInfo) {
  34752. return result;
  34753. }
  34754. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34755. }
  34756. return result;
  34757. };
  34758. // Dispose
  34759. /**
  34760. * Disposes the Submesh.
  34761. * Returns nothing.
  34762. */
  34763. SubMesh.prototype.dispose = function () {
  34764. if (this._linesIndexBuffer) {
  34765. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34766. this._linesIndexBuffer = null;
  34767. }
  34768. // Remove from mesh
  34769. var index = this._mesh.subMeshes.indexOf(this);
  34770. this._mesh.subMeshes.splice(index, 1);
  34771. };
  34772. // Statics
  34773. /**
  34774. * Creates a new Submesh from the passed parameters :
  34775. * - materialIndex (integer) : the index of the main mesh material.
  34776. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34777. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34778. * - mesh (Mesh) : the main mesh to create the submesh from.
  34779. * - renderingMesh (optional Mesh) : rendering mesh.
  34780. */
  34781. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34782. var minVertexIndex = Number.MAX_VALUE;
  34783. var maxVertexIndex = -Number.MAX_VALUE;
  34784. renderingMesh = (renderingMesh || mesh);
  34785. var indices = renderingMesh.getIndices();
  34786. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34787. var vertexIndex = indices[index];
  34788. if (vertexIndex < minVertexIndex)
  34789. minVertexIndex = vertexIndex;
  34790. if (vertexIndex > maxVertexIndex)
  34791. maxVertexIndex = vertexIndex;
  34792. }
  34793. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34794. };
  34795. return SubMesh;
  34796. }(BaseSubMesh));
  34797. BABYLON.SubMesh = SubMesh;
  34798. })(BABYLON || (BABYLON = {}));
  34799. //# sourceMappingURL=babylon.subMesh.js.map
  34800. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34801. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34802. s = arguments[i];
  34803. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34804. t[p] = s[p];
  34805. }
  34806. return t;
  34807. };
  34808. var BABYLON;
  34809. (function (BABYLON) {
  34810. /**
  34811. * Manages the defines for the Material
  34812. */
  34813. var MaterialDefines = /** @class */ (function () {
  34814. function MaterialDefines() {
  34815. this._isDirty = true;
  34816. /** @hidden */
  34817. this._areLightsDirty = true;
  34818. /** @hidden */
  34819. this._areAttributesDirty = true;
  34820. /** @hidden */
  34821. this._areTexturesDirty = true;
  34822. /** @hidden */
  34823. this._areFresnelDirty = true;
  34824. /** @hidden */
  34825. this._areMiscDirty = true;
  34826. /** @hidden */
  34827. this._areImageProcessingDirty = true;
  34828. /** @hidden */
  34829. this._normals = false;
  34830. /** @hidden */
  34831. this._uvs = false;
  34832. /** @hidden */
  34833. this._needNormals = false;
  34834. /** @hidden */
  34835. this._needUVs = false;
  34836. }
  34837. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34838. /**
  34839. * Specifies if the material needs to be re-calculated
  34840. */
  34841. get: function () {
  34842. return this._isDirty;
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. /**
  34848. * Marks the material to indicate that it has been re-calculated
  34849. */
  34850. MaterialDefines.prototype.markAsProcessed = function () {
  34851. this._isDirty = false;
  34852. this._areAttributesDirty = false;
  34853. this._areTexturesDirty = false;
  34854. this._areFresnelDirty = false;
  34855. this._areLightsDirty = false;
  34856. this._areMiscDirty = false;
  34857. this._areImageProcessingDirty = false;
  34858. };
  34859. /**
  34860. * Marks the material to indicate that it needs to be re-calculated
  34861. */
  34862. MaterialDefines.prototype.markAsUnprocessed = function () {
  34863. this._isDirty = true;
  34864. };
  34865. /**
  34866. * Marks the material to indicate all of its defines need to be re-calculated
  34867. */
  34868. MaterialDefines.prototype.markAllAsDirty = function () {
  34869. this._areTexturesDirty = true;
  34870. this._areAttributesDirty = true;
  34871. this._areLightsDirty = true;
  34872. this._areFresnelDirty = true;
  34873. this._areMiscDirty = true;
  34874. this._areImageProcessingDirty = true;
  34875. this._isDirty = true;
  34876. };
  34877. /**
  34878. * Marks the material to indicate that image processing needs to be re-calculated
  34879. */
  34880. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34881. this._areImageProcessingDirty = true;
  34882. this._isDirty = true;
  34883. };
  34884. /**
  34885. * Marks the material to indicate the lights need to be re-calculated
  34886. */
  34887. MaterialDefines.prototype.markAsLightDirty = function () {
  34888. this._areLightsDirty = true;
  34889. this._isDirty = true;
  34890. };
  34891. /**
  34892. * Marks the attribute state as changed
  34893. */
  34894. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34895. this._areAttributesDirty = true;
  34896. this._isDirty = true;
  34897. };
  34898. /**
  34899. * Marks the texture state as changed
  34900. */
  34901. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34902. this._areTexturesDirty = true;
  34903. this._isDirty = true;
  34904. };
  34905. /**
  34906. * Marks the fresnel state as changed
  34907. */
  34908. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34909. this._areFresnelDirty = true;
  34910. this._isDirty = true;
  34911. };
  34912. /**
  34913. * Marks the misc state as changed
  34914. */
  34915. MaterialDefines.prototype.markAsMiscDirty = function () {
  34916. this._areMiscDirty = true;
  34917. this._isDirty = true;
  34918. };
  34919. /**
  34920. * Rebuilds the material defines
  34921. */
  34922. MaterialDefines.prototype.rebuild = function () {
  34923. if (this._keys) {
  34924. delete this._keys;
  34925. }
  34926. this._keys = [];
  34927. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34928. var key = _a[_i];
  34929. if (key[0] === "_") {
  34930. continue;
  34931. }
  34932. this._keys.push(key);
  34933. }
  34934. };
  34935. /**
  34936. * Specifies if two material defines are equal
  34937. * @param other - A material define instance to compare to
  34938. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34939. */
  34940. MaterialDefines.prototype.isEqual = function (other) {
  34941. if (this._keys.length !== other._keys.length) {
  34942. return false;
  34943. }
  34944. for (var index = 0; index < this._keys.length; index++) {
  34945. var prop = this._keys[index];
  34946. if (this[prop] !== other[prop]) {
  34947. return false;
  34948. }
  34949. }
  34950. return true;
  34951. };
  34952. /**
  34953. * Clones this instance's defines to another instance
  34954. * @param other - material defines to clone values to
  34955. */
  34956. MaterialDefines.prototype.cloneTo = function (other) {
  34957. if (this._keys.length !== other._keys.length) {
  34958. other._keys = this._keys.slice(0);
  34959. }
  34960. for (var index = 0; index < this._keys.length; index++) {
  34961. var prop = this._keys[index];
  34962. other[prop] = this[prop];
  34963. }
  34964. };
  34965. /**
  34966. * Resets the material define values
  34967. */
  34968. MaterialDefines.prototype.reset = function () {
  34969. for (var index = 0; index < this._keys.length; index++) {
  34970. var prop = this._keys[index];
  34971. var type = typeof this[prop];
  34972. switch (type) {
  34973. case "number":
  34974. this[prop] = 0;
  34975. break;
  34976. case "string":
  34977. this[prop] = "";
  34978. break;
  34979. default:
  34980. this[prop] = false;
  34981. break;
  34982. }
  34983. }
  34984. };
  34985. /**
  34986. * Converts the material define values to a string
  34987. * @returns - String of material define information
  34988. */
  34989. MaterialDefines.prototype.toString = function () {
  34990. var result = "";
  34991. for (var index = 0; index < this._keys.length; index++) {
  34992. var prop = this._keys[index];
  34993. var value = this[prop];
  34994. var type = typeof value;
  34995. switch (type) {
  34996. case "number":
  34997. case "string":
  34998. result += "#define " + prop + " " + value + "\n";
  34999. break;
  35000. default:
  35001. if (value) {
  35002. result += "#define " + prop + "\n";
  35003. }
  35004. break;
  35005. }
  35006. }
  35007. return result;
  35008. };
  35009. return MaterialDefines;
  35010. }());
  35011. BABYLON.MaterialDefines = MaterialDefines;
  35012. /**
  35013. * Base class for the main features of a material in Babylon.js
  35014. */
  35015. var Material = /** @class */ (function () {
  35016. /**
  35017. * Creates a material instance
  35018. * @param name defines the name of the material
  35019. * @param scene defines the scene to reference
  35020. * @param doNotAdd specifies if the material should be added to the scene
  35021. */
  35022. function Material(name, scene, doNotAdd) {
  35023. /**
  35024. * Specifies if the ready state should be checked on each call
  35025. */
  35026. this.checkReadyOnEveryCall = false;
  35027. /**
  35028. * Specifies if the ready state should be checked once
  35029. */
  35030. this.checkReadyOnlyOnce = false;
  35031. /**
  35032. * The state of the material
  35033. */
  35034. this.state = "";
  35035. /**
  35036. * The alpha value of the material
  35037. */
  35038. this._alpha = 1.0;
  35039. /**
  35040. * Specifies if back face culling is enabled
  35041. */
  35042. this._backFaceCulling = true;
  35043. /**
  35044. * Specifies if the material should be serialized
  35045. */
  35046. this.doNotSerialize = false;
  35047. /**
  35048. * Specifies if the effect should be stored on sub meshes
  35049. */
  35050. this.storeEffectOnSubMeshes = false;
  35051. /**
  35052. * An event triggered when the material is disposed
  35053. */
  35054. this.onDisposeObservable = new BABYLON.Observable();
  35055. /**
  35056. * An event triggered when the material is bound
  35057. */
  35058. this.onBindObservable = new BABYLON.Observable();
  35059. /**
  35060. * An event triggered when the material is unbound
  35061. */
  35062. this.onUnBindObservable = new BABYLON.Observable();
  35063. /**
  35064. * Stores the value of the alpha mode
  35065. */
  35066. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35067. /**
  35068. * Stores the state of the need depth pre-pass value
  35069. */
  35070. this._needDepthPrePass = false;
  35071. /**
  35072. * Specifies if depth writing should be disabled
  35073. */
  35074. this.disableDepthWrite = false;
  35075. /**
  35076. * Specifies if depth writing should be forced
  35077. */
  35078. this.forceDepthWrite = false;
  35079. /**
  35080. * Specifies if there should be a separate pass for culling
  35081. */
  35082. this.separateCullingPass = false;
  35083. /**
  35084. * Stores the state specifing if fog should be enabled
  35085. */
  35086. this._fogEnabled = true;
  35087. /**
  35088. * Stores the size of points
  35089. */
  35090. this.pointSize = 1.0;
  35091. /**
  35092. * Stores the z offset value
  35093. */
  35094. this.zOffset = 0;
  35095. /**
  35096. * Specifies if the material was previously ready
  35097. */
  35098. this._wasPreviouslyReady = false;
  35099. /**
  35100. * Stores the fill mode state
  35101. */
  35102. this._fillMode = Material.TriangleFillMode;
  35103. this.name = name;
  35104. this.id = name || BABYLON.Tools.RandomId();
  35105. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35106. this.uniqueId = this._scene.getUniqueId();
  35107. if (this._scene.useRightHandedSystem) {
  35108. this.sideOrientation = Material.ClockWiseSideOrientation;
  35109. }
  35110. else {
  35111. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35112. }
  35113. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35114. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35115. if (!doNotAdd) {
  35116. this._scene.materials.push(this);
  35117. }
  35118. }
  35119. Object.defineProperty(Material, "TriangleFillMode", {
  35120. /**
  35121. * Returns the triangle fill mode
  35122. */
  35123. get: function () {
  35124. return Material._TriangleFillMode;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. Object.defineProperty(Material, "WireFrameFillMode", {
  35130. /**
  35131. * Returns the wireframe mode
  35132. */
  35133. get: function () {
  35134. return Material._WireFrameFillMode;
  35135. },
  35136. enumerable: true,
  35137. configurable: true
  35138. });
  35139. Object.defineProperty(Material, "PointFillMode", {
  35140. /**
  35141. * Returns the point fill mode
  35142. */
  35143. get: function () {
  35144. return Material._PointFillMode;
  35145. },
  35146. enumerable: true,
  35147. configurable: true
  35148. });
  35149. Object.defineProperty(Material, "PointListDrawMode", {
  35150. /**
  35151. * Returns the point list draw mode
  35152. */
  35153. get: function () {
  35154. return Material._PointListDrawMode;
  35155. },
  35156. enumerable: true,
  35157. configurable: true
  35158. });
  35159. Object.defineProperty(Material, "LineListDrawMode", {
  35160. /**
  35161. * Returns the line list draw mode
  35162. */
  35163. get: function () {
  35164. return Material._LineListDrawMode;
  35165. },
  35166. enumerable: true,
  35167. configurable: true
  35168. });
  35169. Object.defineProperty(Material, "LineLoopDrawMode", {
  35170. /**
  35171. * Returns the line loop draw mode
  35172. */
  35173. get: function () {
  35174. return Material._LineLoopDrawMode;
  35175. },
  35176. enumerable: true,
  35177. configurable: true
  35178. });
  35179. Object.defineProperty(Material, "LineStripDrawMode", {
  35180. /**
  35181. * Returns the line strip draw mode
  35182. */
  35183. get: function () {
  35184. return Material._LineStripDrawMode;
  35185. },
  35186. enumerable: true,
  35187. configurable: true
  35188. });
  35189. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35190. /**
  35191. * Returns the triangle strip draw mode
  35192. */
  35193. get: function () {
  35194. return Material._TriangleStripDrawMode;
  35195. },
  35196. enumerable: true,
  35197. configurable: true
  35198. });
  35199. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35200. /**
  35201. * Returns the triangle fan draw mode
  35202. */
  35203. get: function () {
  35204. return Material._TriangleFanDrawMode;
  35205. },
  35206. enumerable: true,
  35207. configurable: true
  35208. });
  35209. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35210. /**
  35211. * Returns the clock-wise side orientation
  35212. */
  35213. get: function () {
  35214. return Material._ClockWiseSideOrientation;
  35215. },
  35216. enumerable: true,
  35217. configurable: true
  35218. });
  35219. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35220. /**
  35221. * Returns the counter clock-wise side orientation
  35222. */
  35223. get: function () {
  35224. return Material._CounterClockWiseSideOrientation;
  35225. },
  35226. enumerable: true,
  35227. configurable: true
  35228. });
  35229. Object.defineProperty(Material, "TextureDirtyFlag", {
  35230. /**
  35231. * Returns the dirty texture flag value
  35232. */
  35233. get: function () {
  35234. return Material._TextureDirtyFlag;
  35235. },
  35236. enumerable: true,
  35237. configurable: true
  35238. });
  35239. Object.defineProperty(Material, "LightDirtyFlag", {
  35240. /**
  35241. * Returns the dirty light flag value
  35242. */
  35243. get: function () {
  35244. return Material._LightDirtyFlag;
  35245. },
  35246. enumerable: true,
  35247. configurable: true
  35248. });
  35249. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35250. /**
  35251. * Returns the dirty fresnel flag value
  35252. */
  35253. get: function () {
  35254. return Material._FresnelDirtyFlag;
  35255. },
  35256. enumerable: true,
  35257. configurable: true
  35258. });
  35259. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35260. /**
  35261. * Returns the dirty attributes flag value
  35262. */
  35263. get: function () {
  35264. return Material._AttributesDirtyFlag;
  35265. },
  35266. enumerable: true,
  35267. configurable: true
  35268. });
  35269. Object.defineProperty(Material, "MiscDirtyFlag", {
  35270. /**
  35271. * Returns the dirty misc flag value
  35272. */
  35273. get: function () {
  35274. return Material._MiscDirtyFlag;
  35275. },
  35276. enumerable: true,
  35277. configurable: true
  35278. });
  35279. Object.defineProperty(Material.prototype, "alpha", {
  35280. /**
  35281. * Gets the alpha value of the material
  35282. */
  35283. get: function () {
  35284. return this._alpha;
  35285. },
  35286. /**
  35287. * Sets the alpha value of the material
  35288. */
  35289. set: function (value) {
  35290. if (this._alpha === value) {
  35291. return;
  35292. }
  35293. this._alpha = value;
  35294. this.markAsDirty(Material.MiscDirtyFlag);
  35295. },
  35296. enumerable: true,
  35297. configurable: true
  35298. });
  35299. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35300. /**
  35301. * Gets the back-face culling state
  35302. */
  35303. get: function () {
  35304. return this._backFaceCulling;
  35305. },
  35306. /**
  35307. * Sets the back-face culling state
  35308. */
  35309. set: function (value) {
  35310. if (this._backFaceCulling === value) {
  35311. return;
  35312. }
  35313. this._backFaceCulling = value;
  35314. this.markAsDirty(Material.TextureDirtyFlag);
  35315. },
  35316. enumerable: true,
  35317. configurable: true
  35318. });
  35319. Object.defineProperty(Material.prototype, "onDispose", {
  35320. /**
  35321. * Called during a dispose event
  35322. */
  35323. set: function (callback) {
  35324. if (this._onDisposeObserver) {
  35325. this.onDisposeObservable.remove(this._onDisposeObserver);
  35326. }
  35327. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35328. },
  35329. enumerable: true,
  35330. configurable: true
  35331. });
  35332. Object.defineProperty(Material.prototype, "onBind", {
  35333. /**
  35334. * Called during a bind event
  35335. */
  35336. set: function (callback) {
  35337. if (this._onBindObserver) {
  35338. this.onBindObservable.remove(this._onBindObserver);
  35339. }
  35340. this._onBindObserver = this.onBindObservable.add(callback);
  35341. },
  35342. enumerable: true,
  35343. configurable: true
  35344. });
  35345. Object.defineProperty(Material.prototype, "alphaMode", {
  35346. /**
  35347. * Gets the value of the alpha mode
  35348. */
  35349. get: function () {
  35350. return this._alphaMode;
  35351. },
  35352. /**
  35353. * Sets the value of the alpha mode.
  35354. *
  35355. * | Value | Type | Description |
  35356. * | --- | --- | --- |
  35357. * | 0 | ALPHA_DISABLE | |
  35358. * | 1 | ALPHA_ADD | |
  35359. * | 2 | ALPHA_COMBINE | |
  35360. * | 3 | ALPHA_SUBTRACT | |
  35361. * | 4 | ALPHA_MULTIPLY | |
  35362. * | 5 | ALPHA_MAXIMIZED | |
  35363. * | 6 | ALPHA_ONEONE | |
  35364. * | 7 | ALPHA_PREMULTIPLIED | |
  35365. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35366. * | 9 | ALPHA_INTERPOLATE | |
  35367. * | 10 | ALPHA_SCREENMODE | |
  35368. *
  35369. */
  35370. set: function (value) {
  35371. if (this._alphaMode === value) {
  35372. return;
  35373. }
  35374. this._alphaMode = value;
  35375. this.markAsDirty(Material.TextureDirtyFlag);
  35376. },
  35377. enumerable: true,
  35378. configurable: true
  35379. });
  35380. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35381. /**
  35382. * Gets the depth pre-pass value
  35383. */
  35384. get: function () {
  35385. return this._needDepthPrePass;
  35386. },
  35387. /**
  35388. * Sets the need depth pre-pass value
  35389. */
  35390. set: function (value) {
  35391. if (this._needDepthPrePass === value) {
  35392. return;
  35393. }
  35394. this._needDepthPrePass = value;
  35395. if (this._needDepthPrePass) {
  35396. this.checkReadyOnEveryCall = true;
  35397. }
  35398. },
  35399. enumerable: true,
  35400. configurable: true
  35401. });
  35402. Object.defineProperty(Material.prototype, "fogEnabled", {
  35403. /**
  35404. * Gets the value of the fog enabled state
  35405. */
  35406. get: function () {
  35407. return this._fogEnabled;
  35408. },
  35409. /**
  35410. * Sets the state for enabling fog
  35411. */
  35412. set: function (value) {
  35413. if (this._fogEnabled === value) {
  35414. return;
  35415. }
  35416. this._fogEnabled = value;
  35417. this.markAsDirty(Material.MiscDirtyFlag);
  35418. },
  35419. enumerable: true,
  35420. configurable: true
  35421. });
  35422. Object.defineProperty(Material.prototype, "wireframe", {
  35423. /**
  35424. * Gets a value specifying if wireframe mode is enabled
  35425. */
  35426. get: function () {
  35427. switch (this._fillMode) {
  35428. case Material.WireFrameFillMode:
  35429. case Material.LineListDrawMode:
  35430. case Material.LineLoopDrawMode:
  35431. case Material.LineStripDrawMode:
  35432. return true;
  35433. }
  35434. return this._scene.forceWireframe;
  35435. },
  35436. /**
  35437. * Sets the state of wireframe mode
  35438. */
  35439. set: function (value) {
  35440. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35441. },
  35442. enumerable: true,
  35443. configurable: true
  35444. });
  35445. Object.defineProperty(Material.prototype, "pointsCloud", {
  35446. /**
  35447. * Gets the value specifying if point clouds are enabled
  35448. */
  35449. get: function () {
  35450. switch (this._fillMode) {
  35451. case Material.PointFillMode:
  35452. case Material.PointListDrawMode:
  35453. return true;
  35454. }
  35455. return this._scene.forcePointsCloud;
  35456. },
  35457. /**
  35458. * Sets the state of point cloud mode
  35459. */
  35460. set: function (value) {
  35461. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35462. },
  35463. enumerable: true,
  35464. configurable: true
  35465. });
  35466. Object.defineProperty(Material.prototype, "fillMode", {
  35467. /**
  35468. * Gets the material fill mode
  35469. */
  35470. get: function () {
  35471. return this._fillMode;
  35472. },
  35473. /**
  35474. * Sets the material fill mode
  35475. */
  35476. set: function (value) {
  35477. if (this._fillMode === value) {
  35478. return;
  35479. }
  35480. this._fillMode = value;
  35481. this.markAsDirty(Material.MiscDirtyFlag);
  35482. },
  35483. enumerable: true,
  35484. configurable: true
  35485. });
  35486. /**
  35487. * Returns a string representation of the current material
  35488. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35489. * @returns a string with material information
  35490. */
  35491. Material.prototype.toString = function (fullDetails) {
  35492. var ret = "Name: " + this.name;
  35493. if (fullDetails) {
  35494. }
  35495. return ret;
  35496. };
  35497. /**
  35498. * Gets the class name of the material
  35499. * @returns a string with the class name of the material
  35500. */
  35501. Material.prototype.getClassName = function () {
  35502. return "Material";
  35503. };
  35504. Object.defineProperty(Material.prototype, "isFrozen", {
  35505. /**
  35506. * Specifies if updates for the material been locked
  35507. */
  35508. get: function () {
  35509. return this.checkReadyOnlyOnce;
  35510. },
  35511. enumerable: true,
  35512. configurable: true
  35513. });
  35514. /**
  35515. * Locks updates for the material
  35516. */
  35517. Material.prototype.freeze = function () {
  35518. this.checkReadyOnlyOnce = true;
  35519. };
  35520. /**
  35521. * Unlocks updates for the material
  35522. */
  35523. Material.prototype.unfreeze = function () {
  35524. this.checkReadyOnlyOnce = false;
  35525. };
  35526. /**
  35527. * Specifies if the material is ready to be used
  35528. * @param mesh defines the mesh to check
  35529. * @param useInstances specifies if instances should be used
  35530. * @returns a boolean indicating if the material is ready to be used
  35531. */
  35532. Material.prototype.isReady = function (mesh, useInstances) {
  35533. return true;
  35534. };
  35535. /**
  35536. * Specifies that the submesh is ready to be used
  35537. * @param mesh defines the mesh to check
  35538. * @param subMesh defines which submesh to check
  35539. * @param useInstances specifies that instances should be used
  35540. * @returns a boolean indicating that the submesh is ready or not
  35541. */
  35542. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35543. return false;
  35544. };
  35545. /**
  35546. * Returns the material effect
  35547. * @returns the effect associated with the material
  35548. */
  35549. Material.prototype.getEffect = function () {
  35550. return this._effect;
  35551. };
  35552. /**
  35553. * Returns the current scene
  35554. * @returns a Scene
  35555. */
  35556. Material.prototype.getScene = function () {
  35557. return this._scene;
  35558. };
  35559. /**
  35560. * Specifies if the material will require alpha blending
  35561. * @returns a boolean specifying if alpha blending is needed
  35562. */
  35563. Material.prototype.needAlphaBlending = function () {
  35564. return (this.alpha < 1.0);
  35565. };
  35566. /**
  35567. * Specifies if the mesh will require alpha blending
  35568. * @param mesh defines the mesh to check
  35569. * @returns a boolean specifying if alpha blending is needed for the mesh
  35570. */
  35571. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35572. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35573. };
  35574. /**
  35575. * Specifies if this material should be rendered in alpha test mode
  35576. * @returns a boolean specifying if an alpha test is needed.
  35577. */
  35578. Material.prototype.needAlphaTesting = function () {
  35579. return false;
  35580. };
  35581. /**
  35582. * Gets the texture used for the alpha test
  35583. * @returns the texture to use for alpha testing
  35584. */
  35585. Material.prototype.getAlphaTestTexture = function () {
  35586. return null;
  35587. };
  35588. /**
  35589. * Marks the material to indicate that it needs to be re-calculated
  35590. */
  35591. Material.prototype.markDirty = function () {
  35592. this._wasPreviouslyReady = false;
  35593. };
  35594. /** @hidden */
  35595. Material.prototype._preBind = function (effect, overrideOrientation) {
  35596. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35597. var engine = this._scene.getEngine();
  35598. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35599. var reverse = orientation === Material.ClockWiseSideOrientation;
  35600. engine.enableEffect(effect ? effect : this._effect);
  35601. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35602. return reverse;
  35603. };
  35604. /**
  35605. * Binds the material to the mesh
  35606. * @param world defines the world transformation matrix
  35607. * @param mesh defines the mesh to bind the material to
  35608. */
  35609. Material.prototype.bind = function (world, mesh) {
  35610. };
  35611. /**
  35612. * Binds the submesh to the material
  35613. * @param world defines the world transformation matrix
  35614. * @param mesh defines the mesh containing the submesh
  35615. * @param subMesh defines the submesh to bind the material to
  35616. */
  35617. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35618. };
  35619. /**
  35620. * Binds the world matrix to the material
  35621. * @param world defines the world transformation matrix
  35622. */
  35623. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35624. };
  35625. /**
  35626. * Binds the scene's uniform buffer to the effect.
  35627. * @param effect defines the effect to bind to the scene uniform buffer
  35628. * @param sceneUbo defines the uniform buffer storing scene data
  35629. */
  35630. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35631. sceneUbo.bindToEffect(effect, "Scene");
  35632. };
  35633. /**
  35634. * Binds the view matrix to the effect
  35635. * @param effect defines the effect to bind the view matrix to
  35636. */
  35637. Material.prototype.bindView = function (effect) {
  35638. if (!this._useUBO) {
  35639. effect.setMatrix("view", this.getScene().getViewMatrix());
  35640. }
  35641. else {
  35642. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35643. }
  35644. };
  35645. /**
  35646. * Binds the view projection matrix to the effect
  35647. * @param effect defines the effect to bind the view projection matrix to
  35648. */
  35649. Material.prototype.bindViewProjection = function (effect) {
  35650. if (!this._useUBO) {
  35651. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35652. }
  35653. else {
  35654. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35655. }
  35656. };
  35657. /**
  35658. * Specifies if material alpha testing should be turned on for the mesh
  35659. * @param mesh defines the mesh to check
  35660. */
  35661. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35662. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35663. };
  35664. /**
  35665. * Processes to execute after binding the material to a mesh
  35666. * @param mesh defines the rendered mesh
  35667. */
  35668. Material.prototype._afterBind = function (mesh) {
  35669. this._scene._cachedMaterial = this;
  35670. if (mesh) {
  35671. this._scene._cachedVisibility = mesh.visibility;
  35672. }
  35673. else {
  35674. this._scene._cachedVisibility = 1;
  35675. }
  35676. if (mesh) {
  35677. this.onBindObservable.notifyObservers(mesh);
  35678. }
  35679. if (this.disableDepthWrite) {
  35680. var engine = this._scene.getEngine();
  35681. this._cachedDepthWriteState = engine.getDepthWrite();
  35682. engine.setDepthWrite(false);
  35683. }
  35684. };
  35685. /**
  35686. * Unbinds the material from the mesh
  35687. */
  35688. Material.prototype.unbind = function () {
  35689. this.onUnBindObservable.notifyObservers(this);
  35690. if (this.disableDepthWrite) {
  35691. var engine = this._scene.getEngine();
  35692. engine.setDepthWrite(this._cachedDepthWriteState);
  35693. }
  35694. };
  35695. /**
  35696. * Gets the active textures from the material
  35697. * @returns an array of textures
  35698. */
  35699. Material.prototype.getActiveTextures = function () {
  35700. return [];
  35701. };
  35702. /**
  35703. * Specifies if the material uses a texture
  35704. * @param texture defines the texture to check against the material
  35705. * @returns a boolean specifying if the material uses the texture
  35706. */
  35707. Material.prototype.hasTexture = function (texture) {
  35708. return false;
  35709. };
  35710. /**
  35711. * Makes a duplicate of the material, and gives it a new name
  35712. * @param name defines the new name for the duplicated material
  35713. * @returns the cloned material
  35714. */
  35715. Material.prototype.clone = function (name) {
  35716. return null;
  35717. };
  35718. /**
  35719. * Gets the meshes bound to the material
  35720. * @returns an array of meshes bound to the material
  35721. */
  35722. Material.prototype.getBindedMeshes = function () {
  35723. var result = new Array();
  35724. for (var index = 0; index < this._scene.meshes.length; index++) {
  35725. var mesh = this._scene.meshes[index];
  35726. if (mesh.material === this) {
  35727. result.push(mesh);
  35728. }
  35729. }
  35730. return result;
  35731. };
  35732. /**
  35733. * Force shader compilation
  35734. * @param mesh defines the mesh associated with this material
  35735. * @param onCompiled defines a function to execute once the material is compiled
  35736. * @param options defines the options to configure the compilation
  35737. */
  35738. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35739. var _this = this;
  35740. var localOptions = __assign({ clipPlane: false }, options);
  35741. var subMesh = new BABYLON.BaseSubMesh();
  35742. var scene = this.getScene();
  35743. var checkReady = function () {
  35744. if (!_this._scene || !_this._scene.getEngine()) {
  35745. return;
  35746. }
  35747. if (subMesh._materialDefines) {
  35748. subMesh._materialDefines._renderId = -1;
  35749. }
  35750. var clipPlaneState = scene.clipPlane;
  35751. if (localOptions.clipPlane) {
  35752. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35753. }
  35754. if (_this.storeEffectOnSubMeshes) {
  35755. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35756. if (onCompiled) {
  35757. onCompiled(_this);
  35758. }
  35759. }
  35760. else {
  35761. setTimeout(checkReady, 16);
  35762. }
  35763. }
  35764. else {
  35765. if (_this.isReady(mesh)) {
  35766. if (onCompiled) {
  35767. onCompiled(_this);
  35768. }
  35769. }
  35770. else {
  35771. setTimeout(checkReady, 16);
  35772. }
  35773. }
  35774. if (localOptions.clipPlane) {
  35775. scene.clipPlane = clipPlaneState;
  35776. }
  35777. };
  35778. checkReady();
  35779. };
  35780. /**
  35781. * Force shader compilation
  35782. * @param mesh defines the mesh that will use this material
  35783. * @param options defines additional options for compiling the shaders
  35784. * @returns a promise that resolves when the compilation completes
  35785. */
  35786. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35787. var _this = this;
  35788. return new Promise(function (resolve) {
  35789. _this.forceCompilation(mesh, function () {
  35790. resolve();
  35791. }, options);
  35792. });
  35793. };
  35794. /**
  35795. * Marks a define in the material to indicate that it needs to be re-computed
  35796. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35797. */
  35798. Material.prototype.markAsDirty = function (flag) {
  35799. if (flag & Material.TextureDirtyFlag) {
  35800. this._markAllSubMeshesAsTexturesDirty();
  35801. }
  35802. if (flag & Material.LightDirtyFlag) {
  35803. this._markAllSubMeshesAsLightsDirty();
  35804. }
  35805. if (flag & Material.FresnelDirtyFlag) {
  35806. this._markAllSubMeshesAsFresnelDirty();
  35807. }
  35808. if (flag & Material.AttributesDirtyFlag) {
  35809. this._markAllSubMeshesAsAttributesDirty();
  35810. }
  35811. if (flag & Material.MiscDirtyFlag) {
  35812. this._markAllSubMeshesAsMiscDirty();
  35813. }
  35814. this.getScene().resetCachedMaterial();
  35815. };
  35816. /**
  35817. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35818. * @param func defines a function which checks material defines against the submeshes
  35819. */
  35820. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35821. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35822. var mesh = _a[_i];
  35823. if (!mesh.subMeshes) {
  35824. continue;
  35825. }
  35826. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35827. var subMesh = _c[_b];
  35828. if (subMesh.getMaterial() !== this) {
  35829. continue;
  35830. }
  35831. if (!subMesh._materialDefines) {
  35832. continue;
  35833. }
  35834. func(subMesh._materialDefines);
  35835. }
  35836. }
  35837. };
  35838. /**
  35839. * Indicates that image processing needs to be re-calculated for all submeshes
  35840. */
  35841. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35842. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35843. };
  35844. /**
  35845. * Indicates that textures need to be re-calculated for all submeshes
  35846. */
  35847. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35848. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35849. };
  35850. /**
  35851. * Indicates that fresnel needs to be re-calculated for all submeshes
  35852. */
  35853. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35854. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35855. };
  35856. /**
  35857. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35858. */
  35859. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35860. this._markAllSubMeshesAsDirty(function (defines) {
  35861. defines.markAsFresnelDirty();
  35862. defines.markAsMiscDirty();
  35863. });
  35864. };
  35865. /**
  35866. * Indicates that lights need to be re-calculated for all submeshes
  35867. */
  35868. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35869. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35870. };
  35871. /**
  35872. * Indicates that attributes need to be re-calculated for all submeshes
  35873. */
  35874. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35875. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35876. };
  35877. /**
  35878. * Indicates that misc needs to be re-calculated for all submeshes
  35879. */
  35880. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35881. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35882. };
  35883. /**
  35884. * Indicates that textures and misc need to be re-calculated for all submeshes
  35885. */
  35886. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35887. this._markAllSubMeshesAsDirty(function (defines) {
  35888. defines.markAsTexturesDirty();
  35889. defines.markAsMiscDirty();
  35890. });
  35891. };
  35892. /**
  35893. * Disposes the material
  35894. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35895. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35896. */
  35897. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35898. // Animations
  35899. this.getScene().stopAnimation(this);
  35900. this.getScene().freeProcessedMaterials();
  35901. // Remove from scene
  35902. var index = this._scene.materials.indexOf(this);
  35903. if (index >= 0) {
  35904. this._scene.materials.splice(index, 1);
  35905. }
  35906. // Remove from meshes
  35907. for (index = 0; index < this._scene.meshes.length; index++) {
  35908. var mesh = this._scene.meshes[index];
  35909. if (mesh.material === this) {
  35910. mesh.material = null;
  35911. if (mesh.geometry) {
  35912. var geometry = (mesh.geometry);
  35913. if (this.storeEffectOnSubMeshes) {
  35914. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35915. var subMesh = _a[_i];
  35916. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35917. if (forceDisposeEffect && subMesh._materialEffect) {
  35918. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35919. }
  35920. }
  35921. }
  35922. else {
  35923. geometry._releaseVertexArrayObject(this._effect);
  35924. }
  35925. }
  35926. }
  35927. }
  35928. this._uniformBuffer.dispose();
  35929. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35930. if (forceDisposeEffect && this._effect) {
  35931. if (!this.storeEffectOnSubMeshes) {
  35932. this._scene.getEngine()._releaseEffect(this._effect);
  35933. }
  35934. this._effect = null;
  35935. }
  35936. // Callback
  35937. this.onDisposeObservable.notifyObservers(this);
  35938. this.onDisposeObservable.clear();
  35939. this.onBindObservable.clear();
  35940. this.onUnBindObservable.clear();
  35941. };
  35942. /**
  35943. * Serializes this material
  35944. * @returns the serialized material object
  35945. */
  35946. Material.prototype.serialize = function () {
  35947. return BABYLON.SerializationHelper.Serialize(this);
  35948. };
  35949. /**
  35950. * Creates a MultiMaterial from parsed MultiMaterial data.
  35951. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35952. * @param scene defines the hosting scene
  35953. * @returns a new MultiMaterial
  35954. */
  35955. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35956. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35957. multiMaterial.id = parsedMultiMaterial.id;
  35958. if (BABYLON.Tags) {
  35959. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35960. }
  35961. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35962. var subMatId = parsedMultiMaterial.materials[matIndex];
  35963. if (subMatId) {
  35964. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35965. }
  35966. else {
  35967. multiMaterial.subMaterials.push(null);
  35968. }
  35969. }
  35970. return multiMaterial;
  35971. };
  35972. /**
  35973. * Creates a material from parsed material data
  35974. * @param parsedMaterial defines parsed material data
  35975. * @param scene defines the hosting scene
  35976. * @param rootUrl defines the root URL to use to load textures
  35977. * @returns a new material
  35978. */
  35979. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35980. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35981. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35982. }
  35983. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35984. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35985. if (!BABYLON.LegacyPBRMaterial) {
  35986. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35987. return;
  35988. }
  35989. }
  35990. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35991. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35992. };
  35993. // Triangle views
  35994. Material._TriangleFillMode = 0;
  35995. Material._WireFrameFillMode = 1;
  35996. Material._PointFillMode = 2;
  35997. // Draw modes
  35998. Material._PointListDrawMode = 3;
  35999. Material._LineListDrawMode = 4;
  36000. Material._LineLoopDrawMode = 5;
  36001. Material._LineStripDrawMode = 6;
  36002. Material._TriangleStripDrawMode = 7;
  36003. Material._TriangleFanDrawMode = 8;
  36004. /**
  36005. * Stores the clock-wise side orientation
  36006. */
  36007. Material._ClockWiseSideOrientation = 0;
  36008. /**
  36009. * Stores the counter clock-wise side orientation
  36010. */
  36011. Material._CounterClockWiseSideOrientation = 1;
  36012. /**
  36013. * The dirty texture flag value
  36014. */
  36015. Material._TextureDirtyFlag = 1;
  36016. /**
  36017. * The dirty light flag value
  36018. */
  36019. Material._LightDirtyFlag = 2;
  36020. /**
  36021. * The dirty fresnel flag value
  36022. */
  36023. Material._FresnelDirtyFlag = 4;
  36024. /**
  36025. * The dirty attribute flag value
  36026. */
  36027. Material._AttributesDirtyFlag = 8;
  36028. /**
  36029. * The dirty misc flag value
  36030. */
  36031. Material._MiscDirtyFlag = 16;
  36032. __decorate([
  36033. BABYLON.serialize()
  36034. ], Material.prototype, "id", void 0);
  36035. __decorate([
  36036. BABYLON.serialize()
  36037. ], Material.prototype, "uniqueId", void 0);
  36038. __decorate([
  36039. BABYLON.serialize()
  36040. ], Material.prototype, "name", void 0);
  36041. __decorate([
  36042. BABYLON.serialize()
  36043. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36044. __decorate([
  36045. BABYLON.serialize()
  36046. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36047. __decorate([
  36048. BABYLON.serialize()
  36049. ], Material.prototype, "state", void 0);
  36050. __decorate([
  36051. BABYLON.serialize("alpha")
  36052. ], Material.prototype, "_alpha", void 0);
  36053. __decorate([
  36054. BABYLON.serialize("backFaceCulling")
  36055. ], Material.prototype, "_backFaceCulling", void 0);
  36056. __decorate([
  36057. BABYLON.serialize()
  36058. ], Material.prototype, "sideOrientation", void 0);
  36059. __decorate([
  36060. BABYLON.serialize("alphaMode")
  36061. ], Material.prototype, "_alphaMode", void 0);
  36062. __decorate([
  36063. BABYLON.serialize()
  36064. ], Material.prototype, "_needDepthPrePass", void 0);
  36065. __decorate([
  36066. BABYLON.serialize()
  36067. ], Material.prototype, "disableDepthWrite", void 0);
  36068. __decorate([
  36069. BABYLON.serialize()
  36070. ], Material.prototype, "forceDepthWrite", void 0);
  36071. __decorate([
  36072. BABYLON.serialize()
  36073. ], Material.prototype, "separateCullingPass", void 0);
  36074. __decorate([
  36075. BABYLON.serialize("fogEnabled")
  36076. ], Material.prototype, "_fogEnabled", void 0);
  36077. __decorate([
  36078. BABYLON.serialize()
  36079. ], Material.prototype, "pointSize", void 0);
  36080. __decorate([
  36081. BABYLON.serialize()
  36082. ], Material.prototype, "zOffset", void 0);
  36083. __decorate([
  36084. BABYLON.serialize()
  36085. ], Material.prototype, "wireframe", null);
  36086. __decorate([
  36087. BABYLON.serialize()
  36088. ], Material.prototype, "pointsCloud", null);
  36089. __decorate([
  36090. BABYLON.serialize()
  36091. ], Material.prototype, "fillMode", null);
  36092. return Material;
  36093. }());
  36094. BABYLON.Material = Material;
  36095. })(BABYLON || (BABYLON = {}));
  36096. //# sourceMappingURL=babylon.material.js.map
  36097. var BABYLON;
  36098. (function (BABYLON) {
  36099. var UniformBuffer = /** @class */ (function () {
  36100. /**
  36101. * Uniform buffer objects.
  36102. *
  36103. * Handles blocks of uniform on the GPU.
  36104. *
  36105. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36106. *
  36107. * For more information, please refer to :
  36108. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36109. */
  36110. function UniformBuffer(engine, data, dynamic) {
  36111. this._engine = engine;
  36112. this._noUBO = !engine.supportsUniformBuffers;
  36113. this._dynamic = dynamic;
  36114. this._data = data || [];
  36115. this._uniformLocations = {};
  36116. this._uniformSizes = {};
  36117. this._uniformLocationPointer = 0;
  36118. this._needSync = false;
  36119. if (this._noUBO) {
  36120. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36121. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36122. this.updateFloat = this._updateFloatForEffect;
  36123. this.updateFloat2 = this._updateFloat2ForEffect;
  36124. this.updateFloat3 = this._updateFloat3ForEffect;
  36125. this.updateFloat4 = this._updateFloat4ForEffect;
  36126. this.updateMatrix = this._updateMatrixForEffect;
  36127. this.updateVector3 = this._updateVector3ForEffect;
  36128. this.updateVector4 = this._updateVector4ForEffect;
  36129. this.updateColor3 = this._updateColor3ForEffect;
  36130. this.updateColor4 = this._updateColor4ForEffect;
  36131. }
  36132. else {
  36133. this._engine._uniformBuffers.push(this);
  36134. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36135. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36136. this.updateFloat = this._updateFloatForUniform;
  36137. this.updateFloat2 = this._updateFloat2ForUniform;
  36138. this.updateFloat3 = this._updateFloat3ForUniform;
  36139. this.updateFloat4 = this._updateFloat4ForUniform;
  36140. this.updateMatrix = this._updateMatrixForUniform;
  36141. this.updateVector3 = this._updateVector3ForUniform;
  36142. this.updateVector4 = this._updateVector4ForUniform;
  36143. this.updateColor3 = this._updateColor3ForUniform;
  36144. this.updateColor4 = this._updateColor4ForUniform;
  36145. }
  36146. }
  36147. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36148. // Properties
  36149. /**
  36150. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36151. * or just falling back on setUniformXXX calls.
  36152. */
  36153. get: function () {
  36154. return !this._noUBO;
  36155. },
  36156. enumerable: true,
  36157. configurable: true
  36158. });
  36159. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36160. /**
  36161. * Indicates if the WebGL underlying uniform buffer is in sync
  36162. * with the javascript cache data.
  36163. */
  36164. get: function () {
  36165. return !this._needSync;
  36166. },
  36167. enumerable: true,
  36168. configurable: true
  36169. });
  36170. /**
  36171. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36172. * Also, a dynamic UniformBuffer will disable cache verification and always
  36173. * update the underlying WebGL uniform buffer to the GPU.
  36174. */
  36175. UniformBuffer.prototype.isDynamic = function () {
  36176. return this._dynamic !== undefined;
  36177. };
  36178. /**
  36179. * The data cache on JS side.
  36180. */
  36181. UniformBuffer.prototype.getData = function () {
  36182. return this._bufferData;
  36183. };
  36184. /**
  36185. * The underlying WebGL Uniform buffer.
  36186. */
  36187. UniformBuffer.prototype.getBuffer = function () {
  36188. return this._buffer;
  36189. };
  36190. /**
  36191. * std140 layout specifies how to align data within an UBO structure.
  36192. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36193. * for specs.
  36194. */
  36195. UniformBuffer.prototype._fillAlignment = function (size) {
  36196. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36197. // and 4x4 matrices
  36198. // TODO : change if other types are used
  36199. var alignment;
  36200. if (size <= 2) {
  36201. alignment = size;
  36202. }
  36203. else {
  36204. alignment = 4;
  36205. }
  36206. if ((this._uniformLocationPointer % alignment) !== 0) {
  36207. var oldPointer = this._uniformLocationPointer;
  36208. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36209. var diff = this._uniformLocationPointer - oldPointer;
  36210. for (var i = 0; i < diff; i++) {
  36211. this._data.push(0);
  36212. }
  36213. }
  36214. };
  36215. /**
  36216. * Adds an uniform in the buffer.
  36217. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36218. * for the layout to be correct !
  36219. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36220. * @param {number|number[]} size Data size, or data directly.
  36221. */
  36222. UniformBuffer.prototype.addUniform = function (name, size) {
  36223. if (this._noUBO) {
  36224. return;
  36225. }
  36226. if (this._uniformLocations[name] !== undefined) {
  36227. // Already existing uniform
  36228. return;
  36229. }
  36230. // This function must be called in the order of the shader layout !
  36231. // size can be the size of the uniform, or data directly
  36232. var data;
  36233. if (size instanceof Array) {
  36234. data = size;
  36235. size = data.length;
  36236. }
  36237. else {
  36238. size = size;
  36239. data = [];
  36240. // Fill with zeros
  36241. for (var i = 0; i < size; i++) {
  36242. data.push(0);
  36243. }
  36244. }
  36245. this._fillAlignment(size);
  36246. this._uniformSizes[name] = size;
  36247. this._uniformLocations[name] = this._uniformLocationPointer;
  36248. this._uniformLocationPointer += size;
  36249. for (var i = 0; i < size; i++) {
  36250. this._data.push(data[i]);
  36251. }
  36252. this._needSync = true;
  36253. };
  36254. /**
  36255. * Wrapper for addUniform.
  36256. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36257. * @param {Matrix} mat A 4x4 matrix.
  36258. */
  36259. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36260. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36261. };
  36262. /**
  36263. * Wrapper for addUniform.
  36264. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36265. * @param {number} x
  36266. * @param {number} y
  36267. */
  36268. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36269. var temp = [x, y];
  36270. this.addUniform(name, temp);
  36271. };
  36272. /**
  36273. * Wrapper for addUniform.
  36274. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36275. * @param {number} x
  36276. * @param {number} y
  36277. * @param {number} z
  36278. */
  36279. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36280. var temp = [x, y, z];
  36281. this.addUniform(name, temp);
  36282. };
  36283. /**
  36284. * Wrapper for addUniform.
  36285. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36286. * @param {Color3} color
  36287. */
  36288. UniformBuffer.prototype.addColor3 = function (name, color) {
  36289. var temp = new Array();
  36290. color.toArray(temp);
  36291. this.addUniform(name, temp);
  36292. };
  36293. /**
  36294. * Wrapper for addUniform.
  36295. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36296. * @param {Color3} color
  36297. * @param {number} alpha
  36298. */
  36299. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36300. var temp = new Array();
  36301. color.toArray(temp);
  36302. temp.push(alpha);
  36303. this.addUniform(name, temp);
  36304. };
  36305. /**
  36306. * Wrapper for addUniform.
  36307. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36308. * @param {Vector3} vector
  36309. */
  36310. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36311. var temp = new Array();
  36312. vector.toArray(temp);
  36313. this.addUniform(name, temp);
  36314. };
  36315. /**
  36316. * Wrapper for addUniform.
  36317. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36318. */
  36319. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36320. this.addUniform(name, 12);
  36321. };
  36322. /**
  36323. * Wrapper for addUniform.
  36324. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36325. */
  36326. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36327. this.addUniform(name, 8);
  36328. };
  36329. /**
  36330. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36331. */
  36332. UniformBuffer.prototype.create = function () {
  36333. if (this._noUBO) {
  36334. return;
  36335. }
  36336. if (this._buffer) {
  36337. return; // nothing to do
  36338. }
  36339. // See spec, alignment must be filled as a vec4
  36340. this._fillAlignment(4);
  36341. this._bufferData = new Float32Array(this._data);
  36342. this._rebuild();
  36343. this._needSync = true;
  36344. };
  36345. UniformBuffer.prototype._rebuild = function () {
  36346. if (this._noUBO) {
  36347. return;
  36348. }
  36349. if (this._dynamic) {
  36350. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36351. }
  36352. else {
  36353. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36354. }
  36355. };
  36356. /**
  36357. * Updates the WebGL Uniform Buffer on the GPU.
  36358. * If the `dynamic` flag is set to true, no cache comparison is done.
  36359. * Otherwise, the buffer will be updated only if the cache differs.
  36360. */
  36361. UniformBuffer.prototype.update = function () {
  36362. if (!this._buffer) {
  36363. this.create();
  36364. return;
  36365. }
  36366. if (!this._dynamic && !this._needSync) {
  36367. return;
  36368. }
  36369. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36370. this._needSync = false;
  36371. };
  36372. /**
  36373. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36374. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36375. * @param {number[]|Float32Array} data Flattened data
  36376. * @param {number} size Size of the data.
  36377. */
  36378. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36379. var location = this._uniformLocations[uniformName];
  36380. if (location === undefined) {
  36381. if (this._buffer) {
  36382. // Cannot add an uniform if the buffer is already created
  36383. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36384. return;
  36385. }
  36386. this.addUniform(uniformName, size);
  36387. location = this._uniformLocations[uniformName];
  36388. }
  36389. if (!this._buffer) {
  36390. this.create();
  36391. }
  36392. if (!this._dynamic) {
  36393. // Cache for static uniform buffers
  36394. var changed = false;
  36395. for (var i = 0; i < size; i++) {
  36396. if (this._bufferData[location + i] !== data[i]) {
  36397. changed = true;
  36398. this._bufferData[location + i] = data[i];
  36399. }
  36400. }
  36401. this._needSync = this._needSync || changed;
  36402. }
  36403. else {
  36404. // No cache for dynamic
  36405. for (var i = 0; i < size; i++) {
  36406. this._bufferData[location + i] = data[i];
  36407. }
  36408. }
  36409. };
  36410. // Update methods
  36411. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36412. // To match std140, matrix must be realigned
  36413. for (var i = 0; i < 3; i++) {
  36414. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36415. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36416. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36417. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36418. }
  36419. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36420. };
  36421. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36422. this._currentEffect.setMatrix3x3(name, matrix);
  36423. };
  36424. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36425. this._currentEffect.setMatrix2x2(name, matrix);
  36426. };
  36427. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36428. // To match std140, matrix must be realigned
  36429. for (var i = 0; i < 2; i++) {
  36430. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36431. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36432. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36433. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36434. }
  36435. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36436. };
  36437. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36438. this._currentEffect.setFloat(name, x);
  36439. };
  36440. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36441. UniformBuffer._tempBuffer[0] = x;
  36442. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36443. };
  36444. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36445. if (suffix === void 0) { suffix = ""; }
  36446. this._currentEffect.setFloat2(name + suffix, x, y);
  36447. };
  36448. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36449. if (suffix === void 0) { suffix = ""; }
  36450. UniformBuffer._tempBuffer[0] = x;
  36451. UniformBuffer._tempBuffer[1] = y;
  36452. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36453. };
  36454. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36455. if (suffix === void 0) { suffix = ""; }
  36456. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36457. };
  36458. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36459. if (suffix === void 0) { suffix = ""; }
  36460. UniformBuffer._tempBuffer[0] = x;
  36461. UniformBuffer._tempBuffer[1] = y;
  36462. UniformBuffer._tempBuffer[2] = z;
  36463. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36464. };
  36465. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36466. if (suffix === void 0) { suffix = ""; }
  36467. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36468. };
  36469. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36470. if (suffix === void 0) { suffix = ""; }
  36471. UniformBuffer._tempBuffer[0] = x;
  36472. UniformBuffer._tempBuffer[1] = y;
  36473. UniformBuffer._tempBuffer[2] = z;
  36474. UniformBuffer._tempBuffer[3] = w;
  36475. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36476. };
  36477. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36478. this._currentEffect.setMatrix(name, mat);
  36479. };
  36480. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36481. this.updateUniform(name, mat.toArray(), 16);
  36482. };
  36483. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36484. this._currentEffect.setVector3(name, vector);
  36485. };
  36486. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36487. vector.toArray(UniformBuffer._tempBuffer);
  36488. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36489. };
  36490. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36491. this._currentEffect.setVector4(name, vector);
  36492. };
  36493. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36494. vector.toArray(UniformBuffer._tempBuffer);
  36495. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36496. };
  36497. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36498. if (suffix === void 0) { suffix = ""; }
  36499. this._currentEffect.setColor3(name + suffix, color);
  36500. };
  36501. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36502. if (suffix === void 0) { suffix = ""; }
  36503. color.toArray(UniformBuffer._tempBuffer);
  36504. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36505. };
  36506. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36507. if (suffix === void 0) { suffix = ""; }
  36508. this._currentEffect.setColor4(name + suffix, color, alpha);
  36509. };
  36510. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36511. if (suffix === void 0) { suffix = ""; }
  36512. color.toArray(UniformBuffer._tempBuffer);
  36513. UniformBuffer._tempBuffer[3] = alpha;
  36514. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36515. };
  36516. /**
  36517. * Sets a sampler uniform on the effect.
  36518. * @param {string} name Name of the sampler.
  36519. * @param {Texture} texture
  36520. */
  36521. UniformBuffer.prototype.setTexture = function (name, texture) {
  36522. this._currentEffect.setTexture(name, texture);
  36523. };
  36524. /**
  36525. * Directly updates the value of the uniform in the cache AND on the GPU.
  36526. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36527. * @param {number[]|Float32Array} data Flattened data
  36528. */
  36529. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36530. this.updateUniform(uniformName, data, data.length);
  36531. this.update();
  36532. };
  36533. /**
  36534. * Binds this uniform buffer to an effect.
  36535. * @param {Effect} effect
  36536. * @param {string} name Name of the uniform block in the shader.
  36537. */
  36538. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36539. this._currentEffect = effect;
  36540. if (this._noUBO || !this._buffer) {
  36541. return;
  36542. }
  36543. effect.bindUniformBuffer(this._buffer, name);
  36544. };
  36545. /**
  36546. * Disposes the uniform buffer.
  36547. */
  36548. UniformBuffer.prototype.dispose = function () {
  36549. if (this._noUBO) {
  36550. return;
  36551. }
  36552. var index = this._engine._uniformBuffers.indexOf(this);
  36553. if (index !== -1) {
  36554. this._engine._uniformBuffers.splice(index, 1);
  36555. }
  36556. if (!this._buffer) {
  36557. return;
  36558. }
  36559. if (this._engine._releaseBuffer(this._buffer)) {
  36560. this._buffer = null;
  36561. }
  36562. };
  36563. // Pool for avoiding memory leaks
  36564. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36565. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36566. return UniformBuffer;
  36567. }());
  36568. BABYLON.UniformBuffer = UniformBuffer;
  36569. })(BABYLON || (BABYLON = {}));
  36570. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36571. var BABYLON;
  36572. (function (BABYLON) {
  36573. /**
  36574. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36575. */
  36576. var VertexData = /** @class */ (function () {
  36577. function VertexData() {
  36578. }
  36579. /**
  36580. * Uses the passed data array to set the set the values for the specified kind of data
  36581. * @param data a linear array of floating numbers
  36582. * @param kind the type of data that is being set, eg positions, colors etc
  36583. */
  36584. VertexData.prototype.set = function (data, kind) {
  36585. switch (kind) {
  36586. case BABYLON.VertexBuffer.PositionKind:
  36587. this.positions = data;
  36588. break;
  36589. case BABYLON.VertexBuffer.NormalKind:
  36590. this.normals = data;
  36591. break;
  36592. case BABYLON.VertexBuffer.TangentKind:
  36593. this.tangents = data;
  36594. break;
  36595. case BABYLON.VertexBuffer.UVKind:
  36596. this.uvs = data;
  36597. break;
  36598. case BABYLON.VertexBuffer.UV2Kind:
  36599. this.uvs2 = data;
  36600. break;
  36601. case BABYLON.VertexBuffer.UV3Kind:
  36602. this.uvs3 = data;
  36603. break;
  36604. case BABYLON.VertexBuffer.UV4Kind:
  36605. this.uvs4 = data;
  36606. break;
  36607. case BABYLON.VertexBuffer.UV5Kind:
  36608. this.uvs5 = data;
  36609. break;
  36610. case BABYLON.VertexBuffer.UV6Kind:
  36611. this.uvs6 = data;
  36612. break;
  36613. case BABYLON.VertexBuffer.ColorKind:
  36614. this.colors = data;
  36615. break;
  36616. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36617. this.matricesIndices = data;
  36618. break;
  36619. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36620. this.matricesWeights = data;
  36621. break;
  36622. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36623. this.matricesIndicesExtra = data;
  36624. break;
  36625. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36626. this.matricesWeightsExtra = data;
  36627. break;
  36628. }
  36629. };
  36630. /**
  36631. * Associates the vertexData to the passed Mesh.
  36632. * Sets it as updatable or not (default `false`)
  36633. * @param mesh the mesh the vertexData is applied to
  36634. * @param updatable when used and having the value true allows new data to update the vertexData
  36635. * @returns the VertexData
  36636. */
  36637. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36638. this._applyTo(mesh, updatable);
  36639. return this;
  36640. };
  36641. /**
  36642. * Associates the vertexData to the passed Geometry.
  36643. * Sets it as updatable or not (default `false`)
  36644. * @param geometry the geometry the vertexData is applied to
  36645. * @param updatable when used and having the value true allows new data to update the vertexData
  36646. * @returns VertexData
  36647. */
  36648. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36649. this._applyTo(geometry, updatable);
  36650. return this;
  36651. };
  36652. /**
  36653. * Updates the associated mesh
  36654. * @param mesh the mesh to be updated
  36655. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36656. * @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
  36657. * @returns VertexData
  36658. */
  36659. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36660. this._update(mesh);
  36661. return this;
  36662. };
  36663. /**
  36664. * Updates the associated geometry
  36665. * @param geometry the geometry to be updated
  36666. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36667. * @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
  36668. * @returns VertexData.
  36669. */
  36670. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36671. this._update(geometry);
  36672. return this;
  36673. };
  36674. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36675. if (updatable === void 0) { updatable = false; }
  36676. if (this.positions) {
  36677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36678. }
  36679. if (this.normals) {
  36680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36681. }
  36682. if (this.tangents) {
  36683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36684. }
  36685. if (this.uvs) {
  36686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36687. }
  36688. if (this.uvs2) {
  36689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36690. }
  36691. if (this.uvs3) {
  36692. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36693. }
  36694. if (this.uvs4) {
  36695. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36696. }
  36697. if (this.uvs5) {
  36698. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36699. }
  36700. if (this.uvs6) {
  36701. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36702. }
  36703. if (this.colors) {
  36704. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36705. }
  36706. if (this.matricesIndices) {
  36707. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36708. }
  36709. if (this.matricesWeights) {
  36710. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36711. }
  36712. if (this.matricesIndicesExtra) {
  36713. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36714. }
  36715. if (this.matricesWeightsExtra) {
  36716. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36717. }
  36718. if (this.indices) {
  36719. meshOrGeometry.setIndices(this.indices, null, updatable);
  36720. }
  36721. else {
  36722. meshOrGeometry.setIndices([], null);
  36723. }
  36724. return this;
  36725. };
  36726. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36727. if (this.positions) {
  36728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36729. }
  36730. if (this.normals) {
  36731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36732. }
  36733. if (this.tangents) {
  36734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36735. }
  36736. if (this.uvs) {
  36737. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36738. }
  36739. if (this.uvs2) {
  36740. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36741. }
  36742. if (this.uvs3) {
  36743. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36744. }
  36745. if (this.uvs4) {
  36746. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36747. }
  36748. if (this.uvs5) {
  36749. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36750. }
  36751. if (this.uvs6) {
  36752. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36753. }
  36754. if (this.colors) {
  36755. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36756. }
  36757. if (this.matricesIndices) {
  36758. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36759. }
  36760. if (this.matricesWeights) {
  36761. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36762. }
  36763. if (this.matricesIndicesExtra) {
  36764. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36765. }
  36766. if (this.matricesWeightsExtra) {
  36767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36768. }
  36769. if (this.indices) {
  36770. meshOrGeometry.setIndices(this.indices, null);
  36771. }
  36772. return this;
  36773. };
  36774. /**
  36775. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36776. * @param matrix the transforming matrix
  36777. * @returns the VertexData
  36778. */
  36779. VertexData.prototype.transform = function (matrix) {
  36780. var transformed = BABYLON.Vector3.Zero();
  36781. var index;
  36782. if (this.positions) {
  36783. var position = BABYLON.Vector3.Zero();
  36784. for (index = 0; index < this.positions.length; index += 3) {
  36785. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36786. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36787. this.positions[index] = transformed.x;
  36788. this.positions[index + 1] = transformed.y;
  36789. this.positions[index + 2] = transformed.z;
  36790. }
  36791. }
  36792. if (this.normals) {
  36793. var normal = BABYLON.Vector3.Zero();
  36794. for (index = 0; index < this.normals.length; index += 3) {
  36795. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36796. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36797. this.normals[index] = transformed.x;
  36798. this.normals[index + 1] = transformed.y;
  36799. this.normals[index + 2] = transformed.z;
  36800. }
  36801. }
  36802. if (this.tangents) {
  36803. var tangent = BABYLON.Vector4.Zero();
  36804. var tangentTransformed = BABYLON.Vector4.Zero();
  36805. for (index = 0; index < this.tangents.length; index += 4) {
  36806. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36807. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36808. this.tangents[index] = tangentTransformed.x;
  36809. this.tangents[index + 1] = tangentTransformed.y;
  36810. this.tangents[index + 2] = tangentTransformed.z;
  36811. this.tangents[index + 3] = tangentTransformed.w;
  36812. }
  36813. }
  36814. return this;
  36815. };
  36816. /**
  36817. * Merges the passed VertexData into the current one
  36818. * @param other the VertexData to be merged into the current one
  36819. * @returns the modified VertexData
  36820. */
  36821. VertexData.prototype.merge = function (other) {
  36822. this._validate();
  36823. other._validate();
  36824. if (!this.normals !== !other.normals ||
  36825. !this.tangents !== !other.tangents ||
  36826. !this.uvs !== !other.uvs ||
  36827. !this.uvs2 !== !other.uvs2 ||
  36828. !this.uvs3 !== !other.uvs3 ||
  36829. !this.uvs4 !== !other.uvs4 ||
  36830. !this.uvs5 !== !other.uvs5 ||
  36831. !this.uvs6 !== !other.uvs6 ||
  36832. !this.colors !== !other.colors ||
  36833. !this.matricesIndices !== !other.matricesIndices ||
  36834. !this.matricesWeights !== !other.matricesWeights ||
  36835. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36836. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36837. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36838. }
  36839. if (other.indices) {
  36840. if (!this.indices) {
  36841. this.indices = [];
  36842. }
  36843. var offset = this.positions ? this.positions.length / 3 : 0;
  36844. for (var index = 0; index < other.indices.length; index++) {
  36845. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36846. this.indices.push(other.indices[index] + offset);
  36847. }
  36848. }
  36849. this.positions = this._mergeElement(this.positions, other.positions);
  36850. this.normals = this._mergeElement(this.normals, other.normals);
  36851. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36852. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36853. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36854. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36855. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36856. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36857. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36858. this.colors = this._mergeElement(this.colors, other.colors);
  36859. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36860. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36861. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36862. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36863. return this;
  36864. };
  36865. VertexData.prototype._mergeElement = function (source, other) {
  36866. if (!source) {
  36867. return other;
  36868. }
  36869. if (!other) {
  36870. return source;
  36871. }
  36872. var len = other.length + source.length;
  36873. var isSrcTypedArray = source instanceof Float32Array;
  36874. var isOthTypedArray = other instanceof Float32Array;
  36875. // use non-loop method when the source is Float32Array
  36876. if (isSrcTypedArray) {
  36877. var ret32 = new Float32Array(len);
  36878. ret32.set(source);
  36879. ret32.set(other, source.length);
  36880. return ret32;
  36881. // source is number[], when other is also use concat
  36882. }
  36883. else if (!isOthTypedArray) {
  36884. return source.concat(other);
  36885. // source is a number[], but other is a Float32Array, loop required
  36886. }
  36887. else {
  36888. var ret = source.slice(0); // copy source to a separate array
  36889. for (var i = 0, len = other.length; i < len; i++) {
  36890. ret.push(other[i]);
  36891. }
  36892. return ret;
  36893. }
  36894. };
  36895. VertexData.prototype._validate = function () {
  36896. if (!this.positions) {
  36897. throw new Error("Positions are required");
  36898. }
  36899. var getElementCount = function (kind, values) {
  36900. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36901. if ((values.length % stride) !== 0) {
  36902. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36903. }
  36904. return values.length / stride;
  36905. };
  36906. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36907. var validateElementCount = function (kind, values) {
  36908. var elementCount = getElementCount(kind, values);
  36909. if (elementCount !== positionsElementCount) {
  36910. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36911. }
  36912. };
  36913. if (this.normals)
  36914. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36915. if (this.tangents)
  36916. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36917. if (this.uvs)
  36918. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36919. if (this.uvs2)
  36920. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36921. if (this.uvs3)
  36922. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36923. if (this.uvs4)
  36924. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36925. if (this.uvs5)
  36926. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36927. if (this.uvs6)
  36928. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36929. if (this.colors)
  36930. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36931. if (this.matricesIndices)
  36932. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36933. if (this.matricesWeights)
  36934. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36935. if (this.matricesIndicesExtra)
  36936. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36937. if (this.matricesWeightsExtra)
  36938. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36939. };
  36940. /**
  36941. * Serializes the VertexData
  36942. * @returns a serialized object
  36943. */
  36944. VertexData.prototype.serialize = function () {
  36945. var serializationObject = this.serialize();
  36946. if (this.positions) {
  36947. serializationObject.positions = this.positions;
  36948. }
  36949. if (this.normals) {
  36950. serializationObject.normals = this.normals;
  36951. }
  36952. if (this.tangents) {
  36953. serializationObject.tangents = this.tangents;
  36954. }
  36955. if (this.uvs) {
  36956. serializationObject.uvs = this.uvs;
  36957. }
  36958. if (this.uvs2) {
  36959. serializationObject.uvs2 = this.uvs2;
  36960. }
  36961. if (this.uvs3) {
  36962. serializationObject.uvs3 = this.uvs3;
  36963. }
  36964. if (this.uvs4) {
  36965. serializationObject.uvs4 = this.uvs4;
  36966. }
  36967. if (this.uvs5) {
  36968. serializationObject.uvs5 = this.uvs5;
  36969. }
  36970. if (this.uvs6) {
  36971. serializationObject.uvs6 = this.uvs6;
  36972. }
  36973. if (this.colors) {
  36974. serializationObject.colors = this.colors;
  36975. }
  36976. if (this.matricesIndices) {
  36977. serializationObject.matricesIndices = this.matricesIndices;
  36978. serializationObject.matricesIndices._isExpanded = true;
  36979. }
  36980. if (this.matricesWeights) {
  36981. serializationObject.matricesWeights = this.matricesWeights;
  36982. }
  36983. if (this.matricesIndicesExtra) {
  36984. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36985. serializationObject.matricesIndicesExtra._isExpanded = true;
  36986. }
  36987. if (this.matricesWeightsExtra) {
  36988. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36989. }
  36990. serializationObject.indices = this.indices;
  36991. return serializationObject;
  36992. };
  36993. // Statics
  36994. /**
  36995. * Extracts the vertexData from a mesh
  36996. * @param mesh the mesh from which to extract the VertexData
  36997. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36998. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36999. * @returns the object VertexData associated to the passed mesh
  37000. */
  37001. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37002. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37003. };
  37004. /**
  37005. * Extracts the vertexData from the geometry
  37006. * @param geometry the geometry from which to extract the VertexData
  37007. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37008. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37009. * @returns the object VertexData associated to the passed mesh
  37010. */
  37011. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37012. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37013. };
  37014. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37015. var result = new VertexData();
  37016. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37017. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37018. }
  37019. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37020. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37021. }
  37022. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37023. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37024. }
  37025. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37026. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37027. }
  37028. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37029. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37030. }
  37031. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37032. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37033. }
  37034. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37035. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37036. }
  37037. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37038. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37039. }
  37040. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37041. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37042. }
  37043. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37044. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37045. }
  37046. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37047. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37048. }
  37049. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37050. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37051. }
  37052. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37053. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37054. }
  37055. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37056. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37057. }
  37058. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37059. return result;
  37060. };
  37061. /**
  37062. * Creates the VertexData for a Ribbon
  37063. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37064. * * pathArray array of paths, each of which an array of successive Vector3
  37065. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37066. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37067. * * 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
  37068. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37069. * * 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)
  37070. * * 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)
  37071. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37072. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37073. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37074. * @returns the VertexData of the ribbon
  37075. */
  37076. VertexData.CreateRibbon = function (options) {
  37077. var pathArray = options.pathArray;
  37078. var closeArray = options.closeArray || false;
  37079. var closePath = options.closePath || false;
  37080. var invertUV = options.invertUV || false;
  37081. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37082. var offset = options.offset || defaultOffset;
  37083. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37084. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37085. var customUV = options.uvs;
  37086. var customColors = options.colors;
  37087. var positions = [];
  37088. var indices = [];
  37089. var normals = [];
  37090. var uvs = [];
  37091. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37092. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37093. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37094. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37095. var minlg; // minimal length among all paths from pathArray
  37096. var lg = []; // array of path lengths : nb of vertex per path
  37097. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37098. var p; // path iterator
  37099. var i; // point iterator
  37100. var j; // point iterator
  37101. // if single path in pathArray
  37102. if (pathArray.length < 2) {
  37103. var ar1 = [];
  37104. var ar2 = [];
  37105. for (i = 0; i < pathArray[0].length - offset; i++) {
  37106. ar1.push(pathArray[0][i]);
  37107. ar2.push(pathArray[0][i + offset]);
  37108. }
  37109. pathArray = [ar1, ar2];
  37110. }
  37111. // positions and horizontal distances (u)
  37112. var idc = 0;
  37113. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37114. var path;
  37115. var l;
  37116. minlg = pathArray[0].length;
  37117. var vectlg;
  37118. var dist;
  37119. for (p = 0; p < pathArray.length; p++) {
  37120. uTotalDistance[p] = 0;
  37121. us[p] = [0];
  37122. path = pathArray[p];
  37123. l = path.length;
  37124. minlg = (minlg < l) ? minlg : l;
  37125. j = 0;
  37126. while (j < l) {
  37127. positions.push(path[j].x, path[j].y, path[j].z);
  37128. if (j > 0) {
  37129. vectlg = path[j].subtract(path[j - 1]).length();
  37130. dist = vectlg + uTotalDistance[p];
  37131. us[p].push(dist);
  37132. uTotalDistance[p] = dist;
  37133. }
  37134. j++;
  37135. }
  37136. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37137. j--;
  37138. positions.push(path[0].x, path[0].y, path[0].z);
  37139. vectlg = path[j].subtract(path[0]).length();
  37140. dist = vectlg + uTotalDistance[p];
  37141. us[p].push(dist);
  37142. uTotalDistance[p] = dist;
  37143. }
  37144. lg[p] = l + closePathCorr;
  37145. idx[p] = idc;
  37146. idc += (l + closePathCorr);
  37147. }
  37148. // vertical distances (v)
  37149. var path1;
  37150. var path2;
  37151. var vertex1 = null;
  37152. var vertex2 = null;
  37153. for (i = 0; i < minlg + closePathCorr; i++) {
  37154. vTotalDistance[i] = 0;
  37155. vs[i] = [0];
  37156. for (p = 0; p < pathArray.length - 1; p++) {
  37157. path1 = pathArray[p];
  37158. path2 = pathArray[p + 1];
  37159. if (i === minlg) { // closePath
  37160. vertex1 = path1[0];
  37161. vertex2 = path2[0];
  37162. }
  37163. else {
  37164. vertex1 = path1[i];
  37165. vertex2 = path2[i];
  37166. }
  37167. vectlg = vertex2.subtract(vertex1).length();
  37168. dist = vectlg + vTotalDistance[i];
  37169. vs[i].push(dist);
  37170. vTotalDistance[i] = dist;
  37171. }
  37172. if (closeArray && vertex2 && vertex1) {
  37173. path1 = pathArray[p];
  37174. path2 = pathArray[0];
  37175. if (i === minlg) { // closePath
  37176. vertex2 = path2[0];
  37177. }
  37178. vectlg = vertex2.subtract(vertex1).length();
  37179. dist = vectlg + vTotalDistance[i];
  37180. vTotalDistance[i] = dist;
  37181. }
  37182. }
  37183. // uvs
  37184. var u;
  37185. var v;
  37186. if (customUV) {
  37187. for (p = 0; p < customUV.length; p++) {
  37188. uvs.push(customUV[p].x, customUV[p].y);
  37189. }
  37190. }
  37191. else {
  37192. for (p = 0; p < pathArray.length; p++) {
  37193. for (i = 0; i < minlg + closePathCorr; i++) {
  37194. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37195. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37196. if (invertUV) {
  37197. uvs.push(v, u);
  37198. }
  37199. else {
  37200. uvs.push(u, v);
  37201. }
  37202. }
  37203. }
  37204. }
  37205. // indices
  37206. p = 0; // path index
  37207. var pi = 0; // positions array index
  37208. var l1 = lg[p] - 1; // path1 length
  37209. var l2 = lg[p + 1] - 1; // path2 length
  37210. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37211. var shft = idx[1] - idx[0]; // shift
  37212. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37213. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37214. // 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
  37215. indices.push(pi, pi + shft, pi + 1);
  37216. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37217. pi += 1;
  37218. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37219. p++;
  37220. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37221. shft = idx[0] - idx[p];
  37222. l1 = lg[p] - 1;
  37223. l2 = lg[0] - 1;
  37224. }
  37225. else {
  37226. shft = idx[p + 1] - idx[p];
  37227. l1 = lg[p] - 1;
  37228. l2 = lg[p + 1] - 1;
  37229. }
  37230. pi = idx[p];
  37231. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37232. }
  37233. }
  37234. // normals
  37235. VertexData.ComputeNormals(positions, indices, normals);
  37236. if (closePath) { // update both the first and last vertex normals to their average value
  37237. var indexFirst = 0;
  37238. var indexLast = 0;
  37239. for (p = 0; p < pathArray.length; p++) {
  37240. indexFirst = idx[p] * 3;
  37241. if (p + 1 < pathArray.length) {
  37242. indexLast = (idx[p + 1] - 1) * 3;
  37243. }
  37244. else {
  37245. indexLast = normals.length - 3;
  37246. }
  37247. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37248. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37249. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37250. normals[indexLast] = normals[indexFirst];
  37251. normals[indexLast + 1] = normals[indexFirst + 1];
  37252. normals[indexLast + 2] = normals[indexFirst + 2];
  37253. }
  37254. }
  37255. // sides
  37256. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37257. // Colors
  37258. var colors = null;
  37259. if (customColors) {
  37260. colors = new Float32Array(customColors.length * 4);
  37261. for (var c = 0; c < customColors.length; c++) {
  37262. colors[c * 4] = customColors[c].r;
  37263. colors[c * 4 + 1] = customColors[c].g;
  37264. colors[c * 4 + 2] = customColors[c].b;
  37265. colors[c * 4 + 3] = customColors[c].a;
  37266. }
  37267. }
  37268. // Result
  37269. var vertexData = new VertexData();
  37270. var positions32 = new Float32Array(positions);
  37271. var normals32 = new Float32Array(normals);
  37272. var uvs32 = new Float32Array(uvs);
  37273. vertexData.indices = indices;
  37274. vertexData.positions = positions32;
  37275. vertexData.normals = normals32;
  37276. vertexData.uvs = uvs32;
  37277. if (colors) {
  37278. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37279. }
  37280. if (closePath) {
  37281. vertexData._idx = idx;
  37282. }
  37283. return vertexData;
  37284. };
  37285. /**
  37286. * Creates the VertexData for a box
  37287. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37288. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37289. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37290. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37291. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37292. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37293. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37294. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37295. * * 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)
  37296. * * 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)
  37297. * @returns the VertexData of the box
  37298. */
  37299. VertexData.CreateBox = function (options) {
  37300. var normalsSource = [
  37301. new BABYLON.Vector3(0, 0, 1),
  37302. new BABYLON.Vector3(0, 0, -1),
  37303. new BABYLON.Vector3(1, 0, 0),
  37304. new BABYLON.Vector3(-1, 0, 0),
  37305. new BABYLON.Vector3(0, 1, 0),
  37306. new BABYLON.Vector3(0, -1, 0)
  37307. ];
  37308. var indices = [];
  37309. var positions = [];
  37310. var normals = [];
  37311. var uvs = [];
  37312. var width = options.width || options.size || 1;
  37313. var height = options.height || options.size || 1;
  37314. var depth = options.depth || options.size || 1;
  37315. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37316. var faceUV = options.faceUV || new Array(6);
  37317. var faceColors = options.faceColors;
  37318. var colors = [];
  37319. // default face colors and UV if undefined
  37320. for (var f = 0; f < 6; f++) {
  37321. if (faceUV[f] === undefined) {
  37322. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37323. }
  37324. if (faceColors && faceColors[f] === undefined) {
  37325. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37326. }
  37327. }
  37328. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37329. // Create each face in turn.
  37330. for (var index = 0; index < normalsSource.length; index++) {
  37331. var normal = normalsSource[index];
  37332. // Get two vectors perpendicular to the face normal and to each other.
  37333. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37334. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37335. // Six indices (two triangles) per face.
  37336. var verticesLength = positions.length / 3;
  37337. indices.push(verticesLength);
  37338. indices.push(verticesLength + 1);
  37339. indices.push(verticesLength + 2);
  37340. indices.push(verticesLength);
  37341. indices.push(verticesLength + 2);
  37342. indices.push(verticesLength + 3);
  37343. // Four vertices per face.
  37344. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37345. positions.push(vertex.x, vertex.y, vertex.z);
  37346. normals.push(normal.x, normal.y, normal.z);
  37347. uvs.push(faceUV[index].z, faceUV[index].w);
  37348. if (faceColors) {
  37349. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37350. }
  37351. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37352. positions.push(vertex.x, vertex.y, vertex.z);
  37353. normals.push(normal.x, normal.y, normal.z);
  37354. uvs.push(faceUV[index].x, faceUV[index].w);
  37355. if (faceColors) {
  37356. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37357. }
  37358. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37359. positions.push(vertex.x, vertex.y, vertex.z);
  37360. normals.push(normal.x, normal.y, normal.z);
  37361. uvs.push(faceUV[index].x, faceUV[index].y);
  37362. if (faceColors) {
  37363. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37364. }
  37365. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37366. positions.push(vertex.x, vertex.y, vertex.z);
  37367. normals.push(normal.x, normal.y, normal.z);
  37368. uvs.push(faceUV[index].z, faceUV[index].y);
  37369. if (faceColors) {
  37370. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37371. }
  37372. }
  37373. // sides
  37374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37375. // Result
  37376. var vertexData = new VertexData();
  37377. vertexData.indices = indices;
  37378. vertexData.positions = positions;
  37379. vertexData.normals = normals;
  37380. vertexData.uvs = uvs;
  37381. if (faceColors) {
  37382. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37383. vertexData.colors = totalColors;
  37384. }
  37385. return vertexData;
  37386. };
  37387. /**
  37388. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37389. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37390. * * segments sets the number of horizontal strips optional, default 32
  37391. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37392. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37393. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37394. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37395. * * 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
  37396. * * 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
  37397. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37398. * * 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)
  37399. * * 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)
  37400. * @returns the VertexData of the ellipsoid
  37401. */
  37402. VertexData.CreateSphere = function (options) {
  37403. var segments = options.segments || 32;
  37404. var diameterX = options.diameterX || options.diameter || 1;
  37405. var diameterY = options.diameterY || options.diameter || 1;
  37406. var diameterZ = options.diameterZ || options.diameter || 1;
  37407. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37408. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37409. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37410. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37411. var totalZRotationSteps = 2 + segments;
  37412. var totalYRotationSteps = 2 * totalZRotationSteps;
  37413. var indices = [];
  37414. var positions = [];
  37415. var normals = [];
  37416. var uvs = [];
  37417. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37418. var normalizedZ = zRotationStep / totalZRotationSteps;
  37419. var angleZ = normalizedZ * Math.PI * slice;
  37420. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37421. var normalizedY = yRotationStep / totalYRotationSteps;
  37422. var angleY = normalizedY * Math.PI * 2 * arc;
  37423. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37424. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37425. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37426. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37427. var vertex = complete.multiply(radius);
  37428. var normal = complete.divide(radius).normalize();
  37429. positions.push(vertex.x, vertex.y, vertex.z);
  37430. normals.push(normal.x, normal.y, normal.z);
  37431. uvs.push(normalizedY, normalizedZ);
  37432. }
  37433. if (zRotationStep > 0) {
  37434. var verticesCount = positions.length / 3;
  37435. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37436. indices.push((firstIndex));
  37437. indices.push((firstIndex + 1));
  37438. indices.push(firstIndex + totalYRotationSteps + 1);
  37439. indices.push((firstIndex + totalYRotationSteps + 1));
  37440. indices.push((firstIndex + 1));
  37441. indices.push((firstIndex + totalYRotationSteps + 2));
  37442. }
  37443. }
  37444. }
  37445. // Sides
  37446. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37447. // Result
  37448. var vertexData = new VertexData();
  37449. vertexData.indices = indices;
  37450. vertexData.positions = positions;
  37451. vertexData.normals = normals;
  37452. vertexData.uvs = uvs;
  37453. return vertexData;
  37454. };
  37455. /**
  37456. * Creates the VertexData for a cylinder, cone or prism
  37457. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37458. * * height sets the height (y direction) of the cylinder, optional, default 2
  37459. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37460. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37461. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37462. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37463. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37464. * * 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
  37465. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37466. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37467. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37468. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37469. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37470. * * 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)
  37471. * * 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)
  37472. * @returns the VertexData of the cylinder, cone or prism
  37473. */
  37474. VertexData.CreateCylinder = function (options) {
  37475. var height = options.height || 2;
  37476. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37477. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37478. var tessellation = options.tessellation || 24;
  37479. var subdivisions = options.subdivisions || 1;
  37480. var hasRings = options.hasRings ? true : false;
  37481. var enclose = options.enclose ? true : false;
  37482. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37483. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37484. var faceUV = options.faceUV || new Array(3);
  37485. var faceColors = options.faceColors;
  37486. // default face colors and UV if undefined
  37487. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37488. var ringNb = (hasRings) ? subdivisions : 1;
  37489. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37490. var f;
  37491. for (f = 0; f < surfaceNb; f++) {
  37492. if (faceColors && faceColors[f] === undefined) {
  37493. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37494. }
  37495. }
  37496. for (f = 0; f < surfaceNb; f++) {
  37497. if (faceUV && faceUV[f] === undefined) {
  37498. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37499. }
  37500. }
  37501. var indices = new Array();
  37502. var positions = new Array();
  37503. var normals = new Array();
  37504. var uvs = new Array();
  37505. var colors = new Array();
  37506. var angle_step = Math.PI * 2 * arc / tessellation;
  37507. var angle;
  37508. var h;
  37509. var radius;
  37510. var tan = (diameterBottom - diameterTop) / 2 / height;
  37511. var ringVertex = BABYLON.Vector3.Zero();
  37512. var ringNormal = BABYLON.Vector3.Zero();
  37513. var ringFirstVertex = BABYLON.Vector3.Zero();
  37514. var ringFirstNormal = BABYLON.Vector3.Zero();
  37515. var quadNormal = BABYLON.Vector3.Zero();
  37516. var Y = BABYLON.Axis.Y;
  37517. // positions, normals, uvs
  37518. var i;
  37519. var j;
  37520. var r;
  37521. var ringIdx = 1;
  37522. var s = 1; // surface index
  37523. var cs = 0;
  37524. var v = 0;
  37525. for (i = 0; i <= subdivisions; i++) {
  37526. h = i / subdivisions;
  37527. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37528. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37529. for (r = 0; r < ringIdx; r++) {
  37530. if (hasRings) {
  37531. s += r;
  37532. }
  37533. if (enclose) {
  37534. s += 2 * r;
  37535. }
  37536. for (j = 0; j <= tessellation; j++) {
  37537. angle = j * angle_step;
  37538. // position
  37539. ringVertex.x = Math.cos(-angle) * radius;
  37540. ringVertex.y = -height / 2 + h * height;
  37541. ringVertex.z = Math.sin(-angle) * radius;
  37542. // normal
  37543. if (diameterTop === 0 && i === subdivisions) {
  37544. // if no top cap, reuse former normals
  37545. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37546. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37547. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37548. }
  37549. else {
  37550. ringNormal.x = ringVertex.x;
  37551. ringNormal.z = ringVertex.z;
  37552. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37553. ringNormal.normalize();
  37554. }
  37555. // keep first ring vertex values for enclose
  37556. if (j === 0) {
  37557. ringFirstVertex.copyFrom(ringVertex);
  37558. ringFirstNormal.copyFrom(ringNormal);
  37559. }
  37560. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37561. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37562. if (hasRings) {
  37563. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37564. }
  37565. else {
  37566. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37567. }
  37568. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37569. if (faceColors) {
  37570. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37571. }
  37572. }
  37573. // if enclose, add four vertices and their dedicated normals
  37574. if (arc !== 1 && enclose) {
  37575. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37576. positions.push(0, ringVertex.y, 0);
  37577. positions.push(0, ringVertex.y, 0);
  37578. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37579. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37580. quadNormal.normalize();
  37581. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37582. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37583. quadNormal.normalize();
  37584. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37585. if (hasRings) {
  37586. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37587. }
  37588. else {
  37589. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37590. }
  37591. uvs.push(faceUV[s + 1].x, v);
  37592. uvs.push(faceUV[s + 1].z, v);
  37593. if (hasRings) {
  37594. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37595. }
  37596. else {
  37597. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37598. }
  37599. uvs.push(faceUV[s + 2].x, v);
  37600. uvs.push(faceUV[s + 2].z, v);
  37601. if (faceColors) {
  37602. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37603. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37604. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37605. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37606. }
  37607. }
  37608. if (cs !== s) {
  37609. cs = s;
  37610. }
  37611. }
  37612. }
  37613. // indices
  37614. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37615. var s;
  37616. i = 0;
  37617. for (s = 0; s < subdivisions; s++) {
  37618. var i0 = 0;
  37619. var i1 = 0;
  37620. var i2 = 0;
  37621. var i3 = 0;
  37622. for (j = 0; j < tessellation; j++) {
  37623. i0 = i * (e + 1) + j;
  37624. i1 = (i + 1) * (e + 1) + j;
  37625. i2 = i * (e + 1) + (j + 1);
  37626. i3 = (i + 1) * (e + 1) + (j + 1);
  37627. indices.push(i0, i1, i2);
  37628. indices.push(i3, i2, i1);
  37629. }
  37630. if (arc !== 1 && enclose) { // if enclose, add two quads
  37631. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37632. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37633. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37634. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37635. }
  37636. i = (hasRings) ? (i + 2) : (i + 1);
  37637. }
  37638. // Caps
  37639. var createCylinderCap = function (isTop) {
  37640. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37641. if (radius === 0) {
  37642. return;
  37643. }
  37644. // Cap positions, normals & uvs
  37645. var angle;
  37646. var circleVector;
  37647. var i;
  37648. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37649. var c = null;
  37650. if (faceColors) {
  37651. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37652. }
  37653. // cap center
  37654. var vbase = positions.length / 3;
  37655. var offset = isTop ? height / 2 : -height / 2;
  37656. var center = new BABYLON.Vector3(0, offset, 0);
  37657. positions.push(center.x, center.y, center.z);
  37658. normals.push(0, isTop ? 1 : -1, 0);
  37659. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37660. if (c) {
  37661. colors.push(c.r, c.g, c.b, c.a);
  37662. }
  37663. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37664. for (i = 0; i <= tessellation; i++) {
  37665. angle = Math.PI * 2 * i * arc / tessellation;
  37666. var cos = Math.cos(-angle);
  37667. var sin = Math.sin(-angle);
  37668. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37669. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37670. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37671. normals.push(0, isTop ? 1 : -1, 0);
  37672. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37673. if (c) {
  37674. colors.push(c.r, c.g, c.b, c.a);
  37675. }
  37676. }
  37677. // Cap indices
  37678. for (i = 0; i < tessellation; i++) {
  37679. if (!isTop) {
  37680. indices.push(vbase);
  37681. indices.push(vbase + (i + 1));
  37682. indices.push(vbase + (i + 2));
  37683. }
  37684. else {
  37685. indices.push(vbase);
  37686. indices.push(vbase + (i + 2));
  37687. indices.push(vbase + (i + 1));
  37688. }
  37689. }
  37690. };
  37691. // add caps to geometry
  37692. createCylinderCap(false);
  37693. createCylinderCap(true);
  37694. // Sides
  37695. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37696. var vertexData = new VertexData();
  37697. vertexData.indices = indices;
  37698. vertexData.positions = positions;
  37699. vertexData.normals = normals;
  37700. vertexData.uvs = uvs;
  37701. if (faceColors) {
  37702. vertexData.colors = colors;
  37703. }
  37704. return vertexData;
  37705. };
  37706. /**
  37707. * Creates the VertexData for a torus
  37708. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37709. * * diameter the diameter of the torus, optional default 1
  37710. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37711. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37712. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37713. * * 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)
  37714. * * 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)
  37715. * @returns the VertexData of the torus
  37716. */
  37717. VertexData.CreateTorus = function (options) {
  37718. var indices = [];
  37719. var positions = [];
  37720. var normals = [];
  37721. var uvs = [];
  37722. var diameter = options.diameter || 1;
  37723. var thickness = options.thickness || 0.5;
  37724. var tessellation = options.tessellation || 16;
  37725. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37726. var stride = tessellation + 1;
  37727. for (var i = 0; i <= tessellation; i++) {
  37728. var u = i / tessellation;
  37729. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37730. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37731. for (var j = 0; j <= tessellation; j++) {
  37732. var v = 1 - j / tessellation;
  37733. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37734. var dx = Math.cos(innerAngle);
  37735. var dy = Math.sin(innerAngle);
  37736. // Create a vertex.
  37737. var normal = new BABYLON.Vector3(dx, dy, 0);
  37738. var position = normal.scale(thickness / 2);
  37739. var textureCoordinate = new BABYLON.Vector2(u, v);
  37740. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37741. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37742. positions.push(position.x, position.y, position.z);
  37743. normals.push(normal.x, normal.y, normal.z);
  37744. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37745. // And create indices for two triangles.
  37746. var nextI = (i + 1) % stride;
  37747. var nextJ = (j + 1) % stride;
  37748. indices.push(i * stride + j);
  37749. indices.push(i * stride + nextJ);
  37750. indices.push(nextI * stride + j);
  37751. indices.push(i * stride + nextJ);
  37752. indices.push(nextI * stride + nextJ);
  37753. indices.push(nextI * stride + j);
  37754. }
  37755. }
  37756. // Sides
  37757. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37758. // Result
  37759. var vertexData = new VertexData();
  37760. vertexData.indices = indices;
  37761. vertexData.positions = positions;
  37762. vertexData.normals = normals;
  37763. vertexData.uvs = uvs;
  37764. return vertexData;
  37765. };
  37766. /**
  37767. * Creates the VertexData of the LineSystem
  37768. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37769. * - lines an array of lines, each line being an array of successive Vector3
  37770. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37771. * @returns the VertexData of the LineSystem
  37772. */
  37773. VertexData.CreateLineSystem = function (options) {
  37774. var indices = [];
  37775. var positions = [];
  37776. var lines = options.lines;
  37777. var colors = options.colors;
  37778. var vertexColors = [];
  37779. var idx = 0;
  37780. for (var l = 0; l < lines.length; l++) {
  37781. var points = lines[l];
  37782. for (var index = 0; index < points.length; index++) {
  37783. positions.push(points[index].x, points[index].y, points[index].z);
  37784. if (colors) {
  37785. var color = colors[l];
  37786. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37787. }
  37788. if (index > 0) {
  37789. indices.push(idx - 1);
  37790. indices.push(idx);
  37791. }
  37792. idx++;
  37793. }
  37794. }
  37795. var vertexData = new VertexData();
  37796. vertexData.indices = indices;
  37797. vertexData.positions = positions;
  37798. if (colors) {
  37799. vertexData.colors = vertexColors;
  37800. }
  37801. return vertexData;
  37802. };
  37803. /**
  37804. * Create the VertexData for a DashedLines
  37805. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37806. * - points an array successive Vector3
  37807. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37808. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37809. * - dashNb the intended total number of dashes, optional, default 200
  37810. * @returns the VertexData for the DashedLines
  37811. */
  37812. VertexData.CreateDashedLines = function (options) {
  37813. var dashSize = options.dashSize || 3;
  37814. var gapSize = options.gapSize || 1;
  37815. var dashNb = options.dashNb || 200;
  37816. var points = options.points;
  37817. var positions = new Array();
  37818. var indices = new Array();
  37819. var curvect = BABYLON.Vector3.Zero();
  37820. var lg = 0;
  37821. var nb = 0;
  37822. var shft = 0;
  37823. var dashshft = 0;
  37824. var curshft = 0;
  37825. var idx = 0;
  37826. var i = 0;
  37827. for (i = 0; i < points.length - 1; i++) {
  37828. points[i + 1].subtractToRef(points[i], curvect);
  37829. lg += curvect.length();
  37830. }
  37831. shft = lg / dashNb;
  37832. dashshft = dashSize * shft / (dashSize + gapSize);
  37833. for (i = 0; i < points.length - 1; i++) {
  37834. points[i + 1].subtractToRef(points[i], curvect);
  37835. nb = Math.floor(curvect.length() / shft);
  37836. curvect.normalize();
  37837. for (var j = 0; j < nb; j++) {
  37838. curshft = shft * j;
  37839. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37840. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37841. indices.push(idx, idx + 1);
  37842. idx += 2;
  37843. }
  37844. }
  37845. // Result
  37846. var vertexData = new VertexData();
  37847. vertexData.positions = positions;
  37848. vertexData.indices = indices;
  37849. return vertexData;
  37850. };
  37851. /**
  37852. * Creates the VertexData for a Ground
  37853. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37854. * - width the width (x direction) of the ground, optional, default 1
  37855. * - height the height (z direction) of the ground, optional, default 1
  37856. * - subdivisions the number of subdivisions per side, optional, default 1
  37857. * @returns the VertexData of the Ground
  37858. */
  37859. VertexData.CreateGround = function (options) {
  37860. var indices = [];
  37861. var positions = [];
  37862. var normals = [];
  37863. var uvs = [];
  37864. var row, col;
  37865. var width = options.width || 1;
  37866. var height = options.height || 1;
  37867. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37868. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37869. for (row = 0; row <= subdivisionsY; row++) {
  37870. for (col = 0; col <= subdivisionsX; col++) {
  37871. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37872. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37873. positions.push(position.x, position.y, position.z);
  37874. normals.push(normal.x, normal.y, normal.z);
  37875. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37876. }
  37877. }
  37878. for (row = 0; row < subdivisionsY; row++) {
  37879. for (col = 0; col < subdivisionsX; col++) {
  37880. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37881. indices.push(col + 1 + row * (subdivisionsX + 1));
  37882. indices.push(col + row * (subdivisionsX + 1));
  37883. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37884. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37885. indices.push(col + row * (subdivisionsX + 1));
  37886. }
  37887. }
  37888. // Result
  37889. var vertexData = new VertexData();
  37890. vertexData.indices = indices;
  37891. vertexData.positions = positions;
  37892. vertexData.normals = normals;
  37893. vertexData.uvs = uvs;
  37894. return vertexData;
  37895. };
  37896. /**
  37897. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37898. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37899. * * xmin the ground minimum X coordinate, optional, default -1
  37900. * * zmin the ground minimum Z coordinate, optional, default -1
  37901. * * xmax the ground maximum X coordinate, optional, default 1
  37902. * * zmax the ground maximum Z coordinate, optional, default 1
  37903. * * 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}
  37904. * * 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}
  37905. * @returns the VertexData of the TiledGround
  37906. */
  37907. VertexData.CreateTiledGround = function (options) {
  37908. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37909. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37910. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37911. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37912. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37913. var precision = options.precision || { w: 1, h: 1 };
  37914. var indices = new Array();
  37915. var positions = new Array();
  37916. var normals = new Array();
  37917. var uvs = new Array();
  37918. var row, col, tileRow, tileCol;
  37919. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37920. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37921. precision.w = (precision.w < 1) ? 1 : precision.w;
  37922. precision.h = (precision.h < 1) ? 1 : precision.h;
  37923. var tileSize = {
  37924. 'w': (xmax - xmin) / subdivisions.w,
  37925. 'h': (zmax - zmin) / subdivisions.h
  37926. };
  37927. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37928. // Indices
  37929. var base = positions.length / 3;
  37930. var rowLength = precision.w + 1;
  37931. for (row = 0; row < precision.h; row++) {
  37932. for (col = 0; col < precision.w; col++) {
  37933. var square = [
  37934. base + col + row * rowLength,
  37935. base + (col + 1) + row * rowLength,
  37936. base + (col + 1) + (row + 1) * rowLength,
  37937. base + col + (row + 1) * rowLength
  37938. ];
  37939. indices.push(square[1]);
  37940. indices.push(square[2]);
  37941. indices.push(square[3]);
  37942. indices.push(square[0]);
  37943. indices.push(square[1]);
  37944. indices.push(square[3]);
  37945. }
  37946. }
  37947. // Position, normals and uvs
  37948. var position = BABYLON.Vector3.Zero();
  37949. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37950. for (row = 0; row <= precision.h; row++) {
  37951. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37952. for (col = 0; col <= precision.w; col++) {
  37953. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37954. position.y = 0;
  37955. positions.push(position.x, position.y, position.z);
  37956. normals.push(normal.x, normal.y, normal.z);
  37957. uvs.push(col / precision.w, row / precision.h);
  37958. }
  37959. }
  37960. }
  37961. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37962. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37963. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37964. }
  37965. }
  37966. // Result
  37967. var vertexData = new VertexData();
  37968. vertexData.indices = indices;
  37969. vertexData.positions = positions;
  37970. vertexData.normals = normals;
  37971. vertexData.uvs = uvs;
  37972. return vertexData;
  37973. };
  37974. /**
  37975. * Creates the VertexData of the Ground designed from a heightmap
  37976. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37977. * * width the width (x direction) of the ground
  37978. * * height the height (z direction) of the ground
  37979. * * subdivisions the number of subdivisions per side
  37980. * * minHeight the minimum altitude on the ground, optional, default 0
  37981. * * maxHeight the maximum altitude on the ground, optional default 1
  37982. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37983. * * buffer the array holding the image color data
  37984. * * bufferWidth the width of image
  37985. * * bufferHeight the height of image
  37986. * @returns the VertexData of the Ground designed from a heightmap
  37987. */
  37988. VertexData.CreateGroundFromHeightMap = function (options) {
  37989. var indices = [];
  37990. var positions = [];
  37991. var normals = [];
  37992. var uvs = [];
  37993. var row, col;
  37994. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37995. // Vertices
  37996. for (row = 0; row <= options.subdivisions; row++) {
  37997. for (col = 0; col <= options.subdivisions; col++) {
  37998. 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));
  37999. // Compute height
  38000. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38001. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38002. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38003. var r = options.buffer[pos] / 255.0;
  38004. var g = options.buffer[pos + 1] / 255.0;
  38005. var b = options.buffer[pos + 2] / 255.0;
  38006. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38007. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38008. // Add vertex
  38009. positions.push(position.x, position.y, position.z);
  38010. normals.push(0, 0, 0);
  38011. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38012. }
  38013. }
  38014. // Indices
  38015. for (row = 0; row < options.subdivisions; row++) {
  38016. for (col = 0; col < options.subdivisions; col++) {
  38017. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38018. indices.push(col + 1 + row * (options.subdivisions + 1));
  38019. indices.push(col + row * (options.subdivisions + 1));
  38020. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38021. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38022. indices.push(col + row * (options.subdivisions + 1));
  38023. }
  38024. }
  38025. // Normals
  38026. VertexData.ComputeNormals(positions, indices, normals);
  38027. // Result
  38028. var vertexData = new VertexData();
  38029. vertexData.indices = indices;
  38030. vertexData.positions = positions;
  38031. vertexData.normals = normals;
  38032. vertexData.uvs = uvs;
  38033. return vertexData;
  38034. };
  38035. /**
  38036. * Creates the VertexData for a Plane
  38037. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38038. * * size sets the width and height of the plane to the value of size, optional default 1
  38039. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38040. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38041. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38042. * * 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)
  38043. * * 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)
  38044. * @returns the VertexData of the box
  38045. */
  38046. VertexData.CreatePlane = function (options) {
  38047. var indices = [];
  38048. var positions = [];
  38049. var normals = [];
  38050. var uvs = [];
  38051. var width = options.width || options.size || 1;
  38052. var height = options.height || options.size || 1;
  38053. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38054. // Vertices
  38055. var halfWidth = width / 2.0;
  38056. var halfHeight = height / 2.0;
  38057. positions.push(-halfWidth, -halfHeight, 0);
  38058. normals.push(0, 0, -1.0);
  38059. uvs.push(0.0, 0.0);
  38060. positions.push(halfWidth, -halfHeight, 0);
  38061. normals.push(0, 0, -1.0);
  38062. uvs.push(1.0, 0.0);
  38063. positions.push(halfWidth, halfHeight, 0);
  38064. normals.push(0, 0, -1.0);
  38065. uvs.push(1.0, 1.0);
  38066. positions.push(-halfWidth, halfHeight, 0);
  38067. normals.push(0, 0, -1.0);
  38068. uvs.push(0.0, 1.0);
  38069. // Indices
  38070. indices.push(0);
  38071. indices.push(1);
  38072. indices.push(2);
  38073. indices.push(0);
  38074. indices.push(2);
  38075. indices.push(3);
  38076. // Sides
  38077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38078. // Result
  38079. var vertexData = new VertexData();
  38080. vertexData.indices = indices;
  38081. vertexData.positions = positions;
  38082. vertexData.normals = normals;
  38083. vertexData.uvs = uvs;
  38084. return vertexData;
  38085. };
  38086. /**
  38087. * Creates the VertexData of the Disc or regular Polygon
  38088. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38089. * * radius the radius of the disc, optional default 0.5
  38090. * * tessellation the number of polygon sides, optional, default 64
  38091. * * 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
  38092. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38093. * * 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)
  38094. * * 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)
  38095. * @returns the VertexData of the box
  38096. */
  38097. VertexData.CreateDisc = function (options) {
  38098. var positions = new Array();
  38099. var indices = new Array();
  38100. var normals = new Array();
  38101. var uvs = new Array();
  38102. var radius = options.radius || 0.5;
  38103. var tessellation = options.tessellation || 64;
  38104. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38105. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38106. // positions and uvs
  38107. positions.push(0, 0, 0); // disc center first
  38108. uvs.push(0.5, 0.5);
  38109. var theta = Math.PI * 2 * arc;
  38110. var step = theta / tessellation;
  38111. for (var a = 0; a < theta; a += step) {
  38112. var x = Math.cos(a);
  38113. var y = Math.sin(a);
  38114. var u = (x + 1) / 2;
  38115. var v = (1 - y) / 2;
  38116. positions.push(radius * x, radius * y, 0);
  38117. uvs.push(u, v);
  38118. }
  38119. if (arc === 1) {
  38120. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38121. uvs.push(uvs[2], uvs[3]);
  38122. }
  38123. //indices
  38124. var vertexNb = positions.length / 3;
  38125. for (var i = 1; i < vertexNb - 1; i++) {
  38126. indices.push(i + 1, 0, i);
  38127. }
  38128. // result
  38129. VertexData.ComputeNormals(positions, indices, normals);
  38130. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38131. var vertexData = new VertexData();
  38132. vertexData.indices = indices;
  38133. vertexData.positions = positions;
  38134. vertexData.normals = normals;
  38135. vertexData.uvs = uvs;
  38136. return vertexData;
  38137. };
  38138. /**
  38139. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38140. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38141. * @param polygon a mesh built from polygonTriangulation.build()
  38142. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38143. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38144. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38145. * @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)
  38146. * @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)
  38147. * @returns the VertexData of the Polygon
  38148. */
  38149. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38150. var faceUV = fUV || new Array(3);
  38151. var faceColors = fColors;
  38152. var colors = [];
  38153. // default face colors and UV if undefined
  38154. for (var f = 0; f < 3; f++) {
  38155. if (faceUV[f] === undefined) {
  38156. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38157. }
  38158. if (faceColors && faceColors[f] === undefined) {
  38159. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38160. }
  38161. }
  38162. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38163. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38164. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38165. var indices = polygon.getIndices();
  38166. // set face colours and textures
  38167. var idx = 0;
  38168. var face = 0;
  38169. for (var index = 0; index < normals.length; index += 3) {
  38170. //Edge Face no. 1
  38171. if (Math.abs(normals[index + 1]) < 0.001) {
  38172. face = 1;
  38173. }
  38174. //Top Face no. 0
  38175. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38176. face = 0;
  38177. }
  38178. //Bottom Face no. 2
  38179. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38180. face = 2;
  38181. }
  38182. idx = index / 3;
  38183. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38184. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38185. if (faceColors) {
  38186. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38187. }
  38188. }
  38189. // sides
  38190. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38191. // Result
  38192. var vertexData = new VertexData();
  38193. vertexData.indices = indices;
  38194. vertexData.positions = positions;
  38195. vertexData.normals = normals;
  38196. vertexData.uvs = uvs;
  38197. if (faceColors) {
  38198. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38199. vertexData.colors = totalColors;
  38200. }
  38201. return vertexData;
  38202. };
  38203. /**
  38204. * Creates the VertexData of the IcoSphere
  38205. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38206. * * radius the radius of the IcoSphere, optional default 1
  38207. * * radiusX allows stretching in the x direction, optional, default radius
  38208. * * radiusY allows stretching in the y direction, optional, default radius
  38209. * * radiusZ allows stretching in the z direction, optional, default radius
  38210. * * flat when true creates a flat shaded mesh, optional, default true
  38211. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38212. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38213. * * 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)
  38214. * * 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)
  38215. * @returns the VertexData of the IcoSphere
  38216. */
  38217. VertexData.CreateIcoSphere = function (options) {
  38218. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38219. var radius = options.radius || 1;
  38220. var flat = (options.flat === undefined) ? true : options.flat;
  38221. var subdivisions = options.subdivisions || 4;
  38222. var radiusX = options.radiusX || radius;
  38223. var radiusY = options.radiusY || radius;
  38224. var radiusZ = options.radiusZ || radius;
  38225. var t = (1 + Math.sqrt(5)) / 2;
  38226. // 12 vertex x,y,z
  38227. var ico_vertices = [
  38228. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38229. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38230. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38231. ];
  38232. // index of 3 vertex makes a face of icopshere
  38233. var ico_indices = [
  38234. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38235. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38236. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38237. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38238. ];
  38239. // vertex for uv have aliased position, not for UV
  38240. var vertices_unalias_id = [
  38241. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38242. // vertex alias
  38243. 0,
  38244. 2,
  38245. 3,
  38246. 3,
  38247. 3,
  38248. 4,
  38249. 7,
  38250. 8,
  38251. 9,
  38252. 9,
  38253. 10,
  38254. 11 // 23: B + 12
  38255. ];
  38256. // uv as integer step (not pixels !)
  38257. var ico_vertexuv = [
  38258. 5, 1, 3, 1, 6, 4, 0, 0,
  38259. 5, 3, 4, 2, 2, 2, 4, 0,
  38260. 2, 0, 1, 1, 6, 0, 6, 2,
  38261. // vertex alias (for same vertex on different faces)
  38262. 0, 4,
  38263. 3, 3,
  38264. 4, 4,
  38265. 3, 1,
  38266. 4, 2,
  38267. 4, 4,
  38268. 0, 2,
  38269. 1, 1,
  38270. 2, 2,
  38271. 3, 3,
  38272. 1, 3,
  38273. 2, 4 // 23: B + 12
  38274. ];
  38275. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38276. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38277. // First island of uv mapping
  38278. // v = 4h 3+ 2
  38279. // v = 3h 9+ 4
  38280. // v = 2h 9+ 5 B
  38281. // v = 1h 9 1 0
  38282. // v = 0h 3 8 7 A
  38283. // u = 0 1 2 3 4 5 6 *a
  38284. // Second island of uv mapping
  38285. // v = 4h 0+ B+ 4+
  38286. // v = 3h A+ 2+
  38287. // v = 2h 7+ 6 3+
  38288. // v = 1h 8+ 3+
  38289. // v = 0h
  38290. // u = 0 1 2 3 4 5 6 *a
  38291. // Face layout on texture UV mapping
  38292. // ============
  38293. // \ 4 /\ 16 / ======
  38294. // \ / \ / /\ 11 /
  38295. // \/ 7 \/ / \ /
  38296. // ======= / 10 \/
  38297. // /\ 17 /\ =======
  38298. // / \ / \ \ 15 /\
  38299. // / 8 \/ 12 \ \ / \
  38300. // ============ \/ 6 \
  38301. // \ 18 /\ ============
  38302. // \ / \ \ 5 /\ 0 /
  38303. // \/ 13 \ \ / \ /
  38304. // ======= \/ 1 \/
  38305. // =============
  38306. // /\ 19 /\ 2 /\
  38307. // / \ / \ / \
  38308. // / 14 \/ 9 \/ 3 \
  38309. // ===================
  38310. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38311. var ustep = 138 / 1024;
  38312. var vstep = 239 / 1024;
  38313. var uoffset = 60 / 1024;
  38314. var voffset = 26 / 1024;
  38315. // Second island should have margin, not to touch the first island
  38316. // avoid any borderline artefact in pixel rounding
  38317. var island_u_offset = -40 / 1024;
  38318. var island_v_offset = +20 / 1024;
  38319. // face is either island 0 or 1 :
  38320. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38321. var island = [
  38322. 0, 0, 0, 0, 1,
  38323. 0, 0, 1, 1, 0,
  38324. 0, 0, 1, 1, 0,
  38325. 0, 1, 1, 1, 0 // 15 - 19
  38326. ];
  38327. var indices = new Array();
  38328. var positions = new Array();
  38329. var normals = new Array();
  38330. var uvs = new Array();
  38331. var current_indice = 0;
  38332. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38333. var face_vertex_pos = new Array(3);
  38334. var face_vertex_uv = new Array(3);
  38335. var v012;
  38336. for (v012 = 0; v012 < 3; v012++) {
  38337. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38338. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38339. }
  38340. // create all with normals
  38341. for (var face = 0; face < 20; face++) {
  38342. // 3 vertex per face
  38343. for (v012 = 0; v012 < 3; v012++) {
  38344. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38345. var v_id = ico_indices[3 * face + v012];
  38346. // vertex have 3D position (x,y,z)
  38347. 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]);
  38348. // Normalize to get normal, then scale to radius
  38349. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38350. // uv Coordinates from vertex ID
  38351. 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);
  38352. }
  38353. // Subdivide the face (interpolate pos, norm, uv)
  38354. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38355. // - norm is linear interpolation of vertex corner normal
  38356. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38357. // - uv is linear interpolation
  38358. //
  38359. // Topology is as below for sub-divide by 2
  38360. // vertex shown as v0,v1,v2
  38361. // interp index is i1 to progress in range [v0,v1[
  38362. // interp index is i2 to progress in range [v0,v2[
  38363. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38364. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38365. //
  38366. //
  38367. // i2 v2
  38368. // ^ ^
  38369. // / / \
  38370. // / / \
  38371. // / / \
  38372. // / / (0,1) \
  38373. // / #---------\
  38374. // / / \ (0,0)'/ \
  38375. // / / \ / \
  38376. // / / \ / \
  38377. // / / (0,0) \ / (1,0) \
  38378. // / #---------#---------\
  38379. // v0 v1
  38380. //
  38381. // --------------------> i1
  38382. //
  38383. // interp of (i1,i2):
  38384. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38385. // along i1 : lerp(x0,x1, i1/(S-i2))
  38386. //
  38387. // centroid of triangle is needed to get help normal computation
  38388. // (c1,c2) are used for centroid location
  38389. var interp_vertex = function (i1, i2, c1, c2) {
  38390. // vertex is interpolated from
  38391. // - face_vertex_pos[0..2]
  38392. // - face_vertex_uv[0..2]
  38393. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38394. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38395. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38396. pos_interp.normalize();
  38397. var vertex_normal;
  38398. if (flat) {
  38399. // in flat mode, recalculate normal as face centroid normal
  38400. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38401. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38402. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38403. }
  38404. else {
  38405. // in smooth mode, recalculate normal from each single vertex position
  38406. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38407. }
  38408. // Vertex normal need correction due to X,Y,Z radius scaling
  38409. vertex_normal.x /= radiusX;
  38410. vertex_normal.y /= radiusY;
  38411. vertex_normal.z /= radiusZ;
  38412. vertex_normal.normalize();
  38413. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38414. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38415. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38416. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38417. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38418. uvs.push(uv_interp.x, uv_interp.y);
  38419. // push each vertex has member of a face
  38420. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38421. indices.push(current_indice);
  38422. current_indice++;
  38423. };
  38424. for (var i2 = 0; i2 < subdivisions; i2++) {
  38425. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38426. // face : (i1,i2) for /\ :
  38427. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38428. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38429. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38430. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38431. if (i1 + i2 + 1 < subdivisions) {
  38432. // face : (i1,i2)' for \/ :
  38433. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38434. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38435. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38436. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38437. }
  38438. }
  38439. }
  38440. }
  38441. // Sides
  38442. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38443. // Result
  38444. var vertexData = new VertexData();
  38445. vertexData.indices = indices;
  38446. vertexData.positions = positions;
  38447. vertexData.normals = normals;
  38448. vertexData.uvs = uvs;
  38449. return vertexData;
  38450. };
  38451. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38452. /**
  38453. * Creates the VertexData for a Polyhedron
  38454. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38455. * * type provided types are:
  38456. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38457. * * 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)
  38458. * * size the size of the IcoSphere, optional default 1
  38459. * * sizeX allows stretching in the x direction, optional, default size
  38460. * * sizeY allows stretching in the y direction, optional, default size
  38461. * * sizeZ allows stretching in the z direction, optional, default size
  38462. * * 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
  38463. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38464. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38465. * * flat when true creates a flat shaded mesh, optional, default true
  38466. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38467. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38468. * * 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)
  38469. * * 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)
  38470. * @returns the VertexData of the Polyhedron
  38471. */
  38472. VertexData.CreatePolyhedron = function (options) {
  38473. // provided polyhedron types :
  38474. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38475. // 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)
  38476. var polyhedra = [];
  38477. 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]] };
  38478. 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]] };
  38479. polyhedra[2] = {
  38480. 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]],
  38481. 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]]
  38482. };
  38483. polyhedra[3] = {
  38484. 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]],
  38485. 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]]
  38486. };
  38487. polyhedra[4] = {
  38488. 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]],
  38489. 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]]
  38490. };
  38491. 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]] };
  38492. 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]] };
  38493. 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]] };
  38494. 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]] };
  38495. 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]] };
  38496. 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]] };
  38497. 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]] };
  38498. 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]] };
  38499. 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]] };
  38500. polyhedra[14] = {
  38501. 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]],
  38502. 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]]
  38503. };
  38504. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38505. var size = options.size;
  38506. var sizeX = options.sizeX || size || 1;
  38507. var sizeY = options.sizeY || size || 1;
  38508. var sizeZ = options.sizeZ || size || 1;
  38509. var data = options.custom || polyhedra[type];
  38510. var nbfaces = data.face.length;
  38511. var faceUV = options.faceUV || new Array(nbfaces);
  38512. var faceColors = options.faceColors;
  38513. var flat = (options.flat === undefined) ? true : options.flat;
  38514. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38515. var positions = new Array();
  38516. var indices = new Array();
  38517. var normals = new Array();
  38518. var uvs = new Array();
  38519. var colors = new Array();
  38520. var index = 0;
  38521. var faceIdx = 0; // face cursor in the array "indexes"
  38522. var indexes = new Array();
  38523. var i = 0;
  38524. var f = 0;
  38525. var u, v, ang, x, y, tmp;
  38526. // default face colors and UV if undefined
  38527. if (flat) {
  38528. for (f = 0; f < nbfaces; f++) {
  38529. if (faceColors && faceColors[f] === undefined) {
  38530. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38531. }
  38532. if (faceUV && faceUV[f] === undefined) {
  38533. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38534. }
  38535. }
  38536. }
  38537. if (!flat) {
  38538. for (i = 0; i < data.vertex.length; i++) {
  38539. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38540. uvs.push(0, 0);
  38541. }
  38542. for (f = 0; f < nbfaces; f++) {
  38543. for (i = 0; i < data.face[f].length - 2; i++) {
  38544. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38545. }
  38546. }
  38547. }
  38548. else {
  38549. for (f = 0; f < nbfaces; f++) {
  38550. var fl = data.face[f].length; // number of vertices of the current face
  38551. ang = 2 * Math.PI / fl;
  38552. x = 0.5 * Math.tan(ang / 2);
  38553. y = 0.5;
  38554. // positions, uvs, colors
  38555. for (i = 0; i < fl; i++) {
  38556. // positions
  38557. 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);
  38558. indexes.push(index);
  38559. index++;
  38560. // uvs
  38561. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38562. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38563. uvs.push(u, v);
  38564. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38565. y = x * Math.sin(ang) + y * Math.cos(ang);
  38566. x = tmp;
  38567. // colors
  38568. if (faceColors) {
  38569. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38570. }
  38571. }
  38572. // indices from indexes
  38573. for (i = 0; i < fl - 2; i++) {
  38574. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38575. }
  38576. faceIdx += fl;
  38577. }
  38578. }
  38579. VertexData.ComputeNormals(positions, indices, normals);
  38580. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38581. var vertexData = new VertexData();
  38582. vertexData.positions = positions;
  38583. vertexData.indices = indices;
  38584. vertexData.normals = normals;
  38585. vertexData.uvs = uvs;
  38586. if (faceColors && flat) {
  38587. vertexData.colors = colors;
  38588. }
  38589. return vertexData;
  38590. };
  38591. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38592. /**
  38593. * Creates the VertexData for a TorusKnot
  38594. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38595. * * radius the radius of the torus knot, optional, default 2
  38596. * * tube the thickness of the tube, optional, default 0.5
  38597. * * radialSegments the number of sides on each tube segments, optional, default 32
  38598. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38599. * * p the number of windings around the z axis, optional, default 2
  38600. * * q the number of windings around the x axis, optional, default 3
  38601. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38602. * * 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)
  38603. * * 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)
  38604. * @returns the VertexData of the Torus Knot
  38605. */
  38606. VertexData.CreateTorusKnot = function (options) {
  38607. var indices = new Array();
  38608. var positions = new Array();
  38609. var normals = new Array();
  38610. var uvs = new Array();
  38611. var radius = options.radius || 2;
  38612. var tube = options.tube || 0.5;
  38613. var radialSegments = options.radialSegments || 32;
  38614. var tubularSegments = options.tubularSegments || 32;
  38615. var p = options.p || 2;
  38616. var q = options.q || 3;
  38617. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38618. // Helper
  38619. var getPos = function (angle) {
  38620. var cu = Math.cos(angle);
  38621. var su = Math.sin(angle);
  38622. var quOverP = q / p * angle;
  38623. var cs = Math.cos(quOverP);
  38624. var tx = radius * (2 + cs) * 0.5 * cu;
  38625. var ty = radius * (2 + cs) * su * 0.5;
  38626. var tz = radius * Math.sin(quOverP) * 0.5;
  38627. return new BABYLON.Vector3(tx, ty, tz);
  38628. };
  38629. // Vertices
  38630. var i;
  38631. var j;
  38632. for (i = 0; i <= radialSegments; i++) {
  38633. var modI = i % radialSegments;
  38634. var u = modI / radialSegments * 2 * p * Math.PI;
  38635. var p1 = getPos(u);
  38636. var p2 = getPos(u + 0.01);
  38637. var tang = p2.subtract(p1);
  38638. var n = p2.add(p1);
  38639. var bitan = BABYLON.Vector3.Cross(tang, n);
  38640. n = BABYLON.Vector3.Cross(bitan, tang);
  38641. bitan.normalize();
  38642. n.normalize();
  38643. for (j = 0; j < tubularSegments; j++) {
  38644. var modJ = j % tubularSegments;
  38645. var v = modJ / tubularSegments * 2 * Math.PI;
  38646. var cx = -tube * Math.cos(v);
  38647. var cy = tube * Math.sin(v);
  38648. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38649. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38650. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38651. uvs.push(i / radialSegments);
  38652. uvs.push(j / tubularSegments);
  38653. }
  38654. }
  38655. for (i = 0; i < radialSegments; i++) {
  38656. for (j = 0; j < tubularSegments; j++) {
  38657. var jNext = (j + 1) % tubularSegments;
  38658. var a = i * tubularSegments + j;
  38659. var b = (i + 1) * tubularSegments + j;
  38660. var c = (i + 1) * tubularSegments + jNext;
  38661. var d = i * tubularSegments + jNext;
  38662. indices.push(d);
  38663. indices.push(b);
  38664. indices.push(a);
  38665. indices.push(d);
  38666. indices.push(c);
  38667. indices.push(b);
  38668. }
  38669. }
  38670. // Normals
  38671. VertexData.ComputeNormals(positions, indices, normals);
  38672. // Sides
  38673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38674. // Result
  38675. var vertexData = new VertexData();
  38676. vertexData.indices = indices;
  38677. vertexData.positions = positions;
  38678. vertexData.normals = normals;
  38679. vertexData.uvs = uvs;
  38680. return vertexData;
  38681. };
  38682. // Tools
  38683. /**
  38684. * Compute normals for given positions and indices
  38685. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38686. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38687. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38688. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38689. * * facetNormals : optional array of facet normals (vector3)
  38690. * * facetPositions : optional array of facet positions (vector3)
  38691. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38692. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38693. * * bInfo : optional bounding info, required for facetPartitioning computation
  38694. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38695. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38696. * * useRightHandedSystem: optional boolean to for right handed system computation
  38697. * * depthSort : optional boolean to enable the facet depth sort computation
  38698. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38699. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38700. */
  38701. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38702. // temporary scalar variables
  38703. var index = 0; // facet index
  38704. var p1p2x = 0.0; // p1p2 vector x coordinate
  38705. var p1p2y = 0.0; // p1p2 vector y coordinate
  38706. var p1p2z = 0.0; // p1p2 vector z coordinate
  38707. var p3p2x = 0.0; // p3p2 vector x coordinate
  38708. var p3p2y = 0.0; // p3p2 vector y coordinate
  38709. var p3p2z = 0.0; // p3p2 vector z coordinate
  38710. var faceNormalx = 0.0; // facet normal x coordinate
  38711. var faceNormaly = 0.0; // facet normal y coordinate
  38712. var faceNormalz = 0.0; // facet normal z coordinate
  38713. var length = 0.0; // facet normal length before normalization
  38714. var v1x = 0; // vector1 x index in the positions array
  38715. var v1y = 0; // vector1 y index in the positions array
  38716. var v1z = 0; // vector1 z index in the positions array
  38717. var v2x = 0; // vector2 x index in the positions array
  38718. var v2y = 0; // vector2 y index in the positions array
  38719. var v2z = 0; // vector2 z index in the positions array
  38720. var v3x = 0; // vector3 x index in the positions array
  38721. var v3y = 0; // vector3 y index in the positions array
  38722. var v3z = 0; // vector3 z index in the positions array
  38723. var computeFacetNormals = false;
  38724. var computeFacetPositions = false;
  38725. var computeFacetPartitioning = false;
  38726. var computeDepthSort = false;
  38727. var faceNormalSign = 1;
  38728. var ratio = 0;
  38729. var distanceTo = null;
  38730. if (options) {
  38731. computeFacetNormals = (options.facetNormals) ? true : false;
  38732. computeFacetPositions = (options.facetPositions) ? true : false;
  38733. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38734. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38735. ratio = options.ratio || 0;
  38736. computeDepthSort = (options.depthSort) ? true : false;
  38737. distanceTo = (options.distanceTo);
  38738. if (computeDepthSort) {
  38739. if (distanceTo === undefined) {
  38740. distanceTo = BABYLON.Vector3.Zero();
  38741. }
  38742. var depthSortedFacets = options.depthSortedFacets;
  38743. }
  38744. }
  38745. // facetPartitioning reinit if needed
  38746. var xSubRatio = 0;
  38747. var ySubRatio = 0;
  38748. var zSubRatio = 0;
  38749. var subSq = 0;
  38750. if (computeFacetPartitioning && options && options.bbSize) {
  38751. var ox = 0; // X partitioning index for facet position
  38752. var oy = 0; // Y partinioning index for facet position
  38753. var oz = 0; // Z partinioning index for facet position
  38754. var b1x = 0; // X partitioning index for facet v1 vertex
  38755. var b1y = 0; // Y partitioning index for facet v1 vertex
  38756. var b1z = 0; // z partitioning index for facet v1 vertex
  38757. var b2x = 0; // X partitioning index for facet v2 vertex
  38758. var b2y = 0; // Y partitioning index for facet v2 vertex
  38759. var b2z = 0; // Z partitioning index for facet v2 vertex
  38760. var b3x = 0; // X partitioning index for facet v3 vertex
  38761. var b3y = 0; // Y partitioning index for facet v3 vertex
  38762. var b3z = 0; // Z partitioning index for facet v3 vertex
  38763. var block_idx_o = 0; // facet barycenter block index
  38764. var block_idx_v1 = 0; // v1 vertex block index
  38765. var block_idx_v2 = 0; // v2 vertex block index
  38766. var block_idx_v3 = 0; // v3 vertex block index
  38767. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38768. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38769. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38770. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38771. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38772. subSq = options.subDiv.max * options.subDiv.max;
  38773. options.facetPartitioning.length = 0;
  38774. }
  38775. // reset the normals
  38776. for (index = 0; index < positions.length; index++) {
  38777. normals[index] = 0.0;
  38778. }
  38779. // Loop : 1 indice triplet = 1 facet
  38780. var nbFaces = (indices.length / 3) | 0;
  38781. for (index = 0; index < nbFaces; index++) {
  38782. // get the indexes of the coordinates of each vertex of the facet
  38783. v1x = indices[index * 3] * 3;
  38784. v1y = v1x + 1;
  38785. v1z = v1x + 2;
  38786. v2x = indices[index * 3 + 1] * 3;
  38787. v2y = v2x + 1;
  38788. v2z = v2x + 2;
  38789. v3x = indices[index * 3 + 2] * 3;
  38790. v3y = v3x + 1;
  38791. v3z = v3x + 2;
  38792. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38793. p1p2y = positions[v1y] - positions[v2y];
  38794. p1p2z = positions[v1z] - positions[v2z];
  38795. p3p2x = positions[v3x] - positions[v2x];
  38796. p3p2y = positions[v3y] - positions[v2y];
  38797. p3p2z = positions[v3z] - positions[v2z];
  38798. // compute the face normal with the cross product
  38799. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38800. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38801. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38802. // normalize this normal and store it in the array facetData
  38803. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38804. length = (length === 0) ? 1.0 : length;
  38805. faceNormalx /= length;
  38806. faceNormaly /= length;
  38807. faceNormalz /= length;
  38808. if (computeFacetNormals && options) {
  38809. options.facetNormals[index].x = faceNormalx;
  38810. options.facetNormals[index].y = faceNormaly;
  38811. options.facetNormals[index].z = faceNormalz;
  38812. }
  38813. if (computeFacetPositions && options) {
  38814. // compute and the facet barycenter coordinates in the array facetPositions
  38815. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38816. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38817. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38818. }
  38819. if (computeFacetPartitioning && options) {
  38820. // store the facet indexes in arrays in the main facetPartitioning array :
  38821. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38822. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38823. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38824. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38825. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38826. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38827. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38828. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38829. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38830. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38831. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38832. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38833. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38834. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38835. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38836. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38837. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38838. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38839. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38840. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38841. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38842. // push each facet index in each block containing the vertex
  38843. options.facetPartitioning[block_idx_v1].push(index);
  38844. if (block_idx_v2 != block_idx_v1) {
  38845. options.facetPartitioning[block_idx_v2].push(index);
  38846. }
  38847. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38848. options.facetPartitioning[block_idx_v3].push(index);
  38849. }
  38850. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38851. options.facetPartitioning[block_idx_o].push(index);
  38852. }
  38853. }
  38854. if (computeDepthSort && options && options.facetPositions) {
  38855. var dsf = depthSortedFacets[index];
  38856. dsf.ind = index * 3;
  38857. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38858. }
  38859. // compute the normals anyway
  38860. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38861. normals[v1y] += faceNormaly;
  38862. normals[v1z] += faceNormalz;
  38863. normals[v2x] += faceNormalx;
  38864. normals[v2y] += faceNormaly;
  38865. normals[v2z] += faceNormalz;
  38866. normals[v3x] += faceNormalx;
  38867. normals[v3y] += faceNormaly;
  38868. normals[v3z] += faceNormalz;
  38869. }
  38870. // last normalization of each normal
  38871. for (index = 0; index < normals.length / 3; index++) {
  38872. faceNormalx = normals[index * 3];
  38873. faceNormaly = normals[index * 3 + 1];
  38874. faceNormalz = normals[index * 3 + 2];
  38875. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38876. length = (length === 0) ? 1.0 : length;
  38877. faceNormalx /= length;
  38878. faceNormaly /= length;
  38879. faceNormalz /= length;
  38880. normals[index * 3] = faceNormalx;
  38881. normals[index * 3 + 1] = faceNormaly;
  38882. normals[index * 3 + 2] = faceNormalz;
  38883. }
  38884. };
  38885. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38886. var li = indices.length;
  38887. var ln = normals.length;
  38888. var i;
  38889. var n;
  38890. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38891. switch (sideOrientation) {
  38892. case BABYLON.Mesh.FRONTSIDE:
  38893. // nothing changed
  38894. break;
  38895. case BABYLON.Mesh.BACKSIDE:
  38896. var tmp;
  38897. // indices
  38898. for (i = 0; i < li; i += 3) {
  38899. tmp = indices[i];
  38900. indices[i] = indices[i + 2];
  38901. indices[i + 2] = tmp;
  38902. }
  38903. // normals
  38904. for (n = 0; n < ln; n++) {
  38905. normals[n] = -normals[n];
  38906. }
  38907. break;
  38908. case BABYLON.Mesh.DOUBLESIDE:
  38909. // positions
  38910. var lp = positions.length;
  38911. var l = lp / 3;
  38912. for (var p = 0; p < lp; p++) {
  38913. positions[lp + p] = positions[p];
  38914. }
  38915. // indices
  38916. for (i = 0; i < li; i += 3) {
  38917. indices[i + li] = indices[i + 2] + l;
  38918. indices[i + 1 + li] = indices[i + 1] + l;
  38919. indices[i + 2 + li] = indices[i] + l;
  38920. }
  38921. // normals
  38922. for (n = 0; n < ln; n++) {
  38923. normals[ln + n] = -normals[n];
  38924. }
  38925. // uvs
  38926. var lu = uvs.length;
  38927. var u = 0;
  38928. for (u = 0; u < lu; u++) {
  38929. uvs[u + lu] = uvs[u];
  38930. }
  38931. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38932. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38933. u = 0;
  38934. for (i = 0; i < lu / 2; i++) {
  38935. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38936. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38937. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38938. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38939. u += 2;
  38940. }
  38941. break;
  38942. }
  38943. };
  38944. /**
  38945. * Applies VertexData created from the imported parameters to the geometry
  38946. * @param parsedVertexData the parsed data from an imported file
  38947. * @param geometry the geometry to apply the VertexData to
  38948. */
  38949. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38950. var vertexData = new VertexData();
  38951. // positions
  38952. var positions = parsedVertexData.positions;
  38953. if (positions) {
  38954. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38955. }
  38956. // normals
  38957. var normals = parsedVertexData.normals;
  38958. if (normals) {
  38959. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38960. }
  38961. // tangents
  38962. var tangents = parsedVertexData.tangents;
  38963. if (tangents) {
  38964. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38965. }
  38966. // uvs
  38967. var uvs = parsedVertexData.uvs;
  38968. if (uvs) {
  38969. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38970. }
  38971. // uv2s
  38972. var uv2s = parsedVertexData.uv2s;
  38973. if (uv2s) {
  38974. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38975. }
  38976. // uv3s
  38977. var uv3s = parsedVertexData.uv3s;
  38978. if (uv3s) {
  38979. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38980. }
  38981. // uv4s
  38982. var uv4s = parsedVertexData.uv4s;
  38983. if (uv4s) {
  38984. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38985. }
  38986. // uv5s
  38987. var uv5s = parsedVertexData.uv5s;
  38988. if (uv5s) {
  38989. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38990. }
  38991. // uv6s
  38992. var uv6s = parsedVertexData.uv6s;
  38993. if (uv6s) {
  38994. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38995. }
  38996. // colors
  38997. var colors = parsedVertexData.colors;
  38998. if (colors) {
  38999. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39000. }
  39001. // matricesIndices
  39002. var matricesIndices = parsedVertexData.matricesIndices;
  39003. if (matricesIndices) {
  39004. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39005. }
  39006. // matricesWeights
  39007. var matricesWeights = parsedVertexData.matricesWeights;
  39008. if (matricesWeights) {
  39009. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39010. }
  39011. // indices
  39012. var indices = parsedVertexData.indices;
  39013. if (indices) {
  39014. vertexData.indices = indices;
  39015. }
  39016. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39017. };
  39018. return VertexData;
  39019. }());
  39020. BABYLON.VertexData = VertexData;
  39021. })(BABYLON || (BABYLON = {}));
  39022. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39023. var BABYLON;
  39024. (function (BABYLON) {
  39025. /**
  39026. * Class used to store geometry data (vertex buffers + index buffer)
  39027. */
  39028. var Geometry = /** @class */ (function () {
  39029. /**
  39030. * Creates a new geometry
  39031. * @param id defines the unique ID
  39032. * @param scene defines the hosting scene
  39033. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39034. * @param updatable defines if geometry must be updatable (false by default)
  39035. * @param mesh defines the mesh that will be associated with the geometry
  39036. */
  39037. function Geometry(id, scene, vertexData, updatable, mesh) {
  39038. if (updatable === void 0) { updatable = false; }
  39039. if (mesh === void 0) { mesh = null; }
  39040. /**
  39041. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39042. */
  39043. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39044. this._totalVertices = 0;
  39045. this._isDisposed = false;
  39046. this._indexBufferIsUpdatable = false;
  39047. this.id = id;
  39048. this._engine = scene.getEngine();
  39049. this._meshes = [];
  39050. this._scene = scene;
  39051. //Init vertex buffer cache
  39052. this._vertexBuffers = {};
  39053. this._indices = [];
  39054. this._updatable = updatable;
  39055. // vertexData
  39056. if (vertexData) {
  39057. this.setAllVerticesData(vertexData, updatable);
  39058. }
  39059. else {
  39060. this._totalVertices = 0;
  39061. this._indices = [];
  39062. }
  39063. if (this._engine.getCaps().vertexArrayObject) {
  39064. this._vertexArrayObjects = {};
  39065. }
  39066. // applyToMesh
  39067. if (mesh) {
  39068. if (mesh.getClassName() === "LinesMesh") {
  39069. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39070. this._updateExtend();
  39071. }
  39072. this.applyToMesh(mesh);
  39073. mesh.computeWorldMatrix(true);
  39074. }
  39075. }
  39076. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39077. /**
  39078. * 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
  39079. */
  39080. get: function () {
  39081. return this._boundingBias;
  39082. },
  39083. /**
  39084. * 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
  39085. */
  39086. set: function (value) {
  39087. if (this._boundingBias && this._boundingBias.equals(value)) {
  39088. return;
  39089. }
  39090. this._boundingBias = value.clone();
  39091. this._updateBoundingInfo(true, null);
  39092. },
  39093. enumerable: true,
  39094. configurable: true
  39095. });
  39096. /**
  39097. * Static function used to attach a new empty geometry to a mesh
  39098. * @param mesh defines the mesh to attach the geometry to
  39099. * @returns the new {BABYLON.Geometry}
  39100. */
  39101. Geometry.CreateGeometryForMesh = function (mesh) {
  39102. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39103. geometry.applyToMesh(mesh);
  39104. return geometry;
  39105. };
  39106. Object.defineProperty(Geometry.prototype, "extend", {
  39107. /**
  39108. * Gets the current extend of the geometry
  39109. */
  39110. get: function () {
  39111. return this._extend;
  39112. },
  39113. enumerable: true,
  39114. configurable: true
  39115. });
  39116. /**
  39117. * Gets the hosting scene
  39118. * @returns the hosting {BABYLON.Scene}
  39119. */
  39120. Geometry.prototype.getScene = function () {
  39121. return this._scene;
  39122. };
  39123. /**
  39124. * Gets the hosting engine
  39125. * @returns the hosting {BABYLON.Engine}
  39126. */
  39127. Geometry.prototype.getEngine = function () {
  39128. return this._engine;
  39129. };
  39130. /**
  39131. * Defines if the geometry is ready to use
  39132. * @returns true if the geometry is ready to be used
  39133. */
  39134. Geometry.prototype.isReady = function () {
  39135. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39136. };
  39137. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39138. /**
  39139. * Gets a value indicating that the geometry should not be serialized
  39140. */
  39141. get: function () {
  39142. for (var index = 0; index < this._meshes.length; index++) {
  39143. if (!this._meshes[index].doNotSerialize) {
  39144. return false;
  39145. }
  39146. }
  39147. return true;
  39148. },
  39149. enumerable: true,
  39150. configurable: true
  39151. });
  39152. /** @hidden */
  39153. Geometry.prototype._rebuild = function () {
  39154. if (this._vertexArrayObjects) {
  39155. this._vertexArrayObjects = {};
  39156. }
  39157. // Index buffer
  39158. if (this._meshes.length !== 0 && this._indices) {
  39159. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39160. }
  39161. // Vertex buffers
  39162. for (var key in this._vertexBuffers) {
  39163. var vertexBuffer = this._vertexBuffers[key];
  39164. vertexBuffer._rebuild();
  39165. }
  39166. };
  39167. /**
  39168. * Affects all geometry data in one call
  39169. * @param vertexData defines the geometry data
  39170. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39171. */
  39172. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39173. vertexData.applyToGeometry(this, updatable);
  39174. this.notifyUpdate();
  39175. };
  39176. /**
  39177. * Set specific vertex data
  39178. * @param kind defines the data kind (Position, normal, etc...)
  39179. * @param data defines the vertex data to use
  39180. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39181. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39182. */
  39183. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39184. if (updatable === void 0) { updatable = false; }
  39185. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39186. this.setVerticesBuffer(buffer);
  39187. };
  39188. /**
  39189. * Removes a specific vertex data
  39190. * @param kind defines the data kind (Position, normal, etc...)
  39191. */
  39192. Geometry.prototype.removeVerticesData = function (kind) {
  39193. if (this._vertexBuffers[kind]) {
  39194. this._vertexBuffers[kind].dispose();
  39195. delete this._vertexBuffers[kind];
  39196. }
  39197. };
  39198. /**
  39199. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39200. * @param buffer defines the vertex buffer to use
  39201. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39202. */
  39203. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39204. if (totalVertices === void 0) { totalVertices = null; }
  39205. var kind = buffer.getKind();
  39206. if (this._vertexBuffers[kind]) {
  39207. this._vertexBuffers[kind].dispose();
  39208. }
  39209. this._vertexBuffers[kind] = buffer;
  39210. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39211. var data = buffer.getData();
  39212. if (totalVertices != null) {
  39213. this._totalVertices = totalVertices;
  39214. }
  39215. else {
  39216. if (data != null) {
  39217. this._totalVertices = data.length / (buffer.byteStride / 4);
  39218. }
  39219. }
  39220. this._updateExtend(data);
  39221. this._resetPointsArrayCache();
  39222. var meshes = this._meshes;
  39223. var numOfMeshes = meshes.length;
  39224. for (var index = 0; index < numOfMeshes; index++) {
  39225. var mesh = meshes[index];
  39226. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39227. mesh._createGlobalSubMesh(false);
  39228. mesh.computeWorldMatrix(true);
  39229. }
  39230. }
  39231. this.notifyUpdate(kind);
  39232. if (this._vertexArrayObjects) {
  39233. this._disposeVertexArrayObjects();
  39234. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39235. }
  39236. };
  39237. /**
  39238. * Update a specific vertex buffer
  39239. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39240. * It will do nothing if the buffer is not updatable
  39241. * @param kind defines the data kind (Position, normal, etc...)
  39242. * @param data defines the data to use
  39243. * @param offset defines the offset in the target buffer where to store the data
  39244. * @param useBytes set to true if the offset is in bytes
  39245. */
  39246. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39247. if (useBytes === void 0) { useBytes = false; }
  39248. var vertexBuffer = this.getVertexBuffer(kind);
  39249. if (!vertexBuffer) {
  39250. return;
  39251. }
  39252. vertexBuffer.updateDirectly(data, offset, useBytes);
  39253. this.notifyUpdate(kind);
  39254. };
  39255. /**
  39256. * Update a specific vertex buffer
  39257. * This function will create a new buffer if the current one is not updatable
  39258. * @param kind defines the data kind (Position, normal, etc...)
  39259. * @param data defines the data to use
  39260. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39261. */
  39262. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39263. if (updateExtends === void 0) { updateExtends = false; }
  39264. var vertexBuffer = this.getVertexBuffer(kind);
  39265. if (!vertexBuffer) {
  39266. return;
  39267. }
  39268. vertexBuffer.update(data);
  39269. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39270. this._updateBoundingInfo(updateExtends, data);
  39271. }
  39272. this.notifyUpdate(kind);
  39273. };
  39274. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39275. if (updateExtends) {
  39276. this._updateExtend(data);
  39277. }
  39278. var meshes = this._meshes;
  39279. var numOfMeshes = meshes.length;
  39280. this._resetPointsArrayCache();
  39281. for (var index = 0; index < numOfMeshes; index++) {
  39282. var mesh = meshes[index];
  39283. if (updateExtends) {
  39284. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39285. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39286. var subMesh = mesh.subMeshes[subIndex];
  39287. subMesh.refreshBoundingInfo();
  39288. }
  39289. }
  39290. }
  39291. };
  39292. /** @hidden */
  39293. Geometry.prototype._bind = function (effect, indexToBind) {
  39294. if (!effect) {
  39295. return;
  39296. }
  39297. if (indexToBind === undefined) {
  39298. indexToBind = this._indexBuffer;
  39299. }
  39300. var vbs = this.getVertexBuffers();
  39301. if (!vbs) {
  39302. return;
  39303. }
  39304. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39305. this._engine.bindBuffers(vbs, indexToBind, effect);
  39306. return;
  39307. }
  39308. // Using VAO
  39309. if (!this._vertexArrayObjects[effect.key]) {
  39310. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39311. }
  39312. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39313. };
  39314. /**
  39315. * Gets total number of vertices
  39316. * @returns the total number of vertices
  39317. */
  39318. Geometry.prototype.getTotalVertices = function () {
  39319. if (!this.isReady()) {
  39320. return 0;
  39321. }
  39322. return this._totalVertices;
  39323. };
  39324. /**
  39325. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39326. * @param kind defines the data kind (Position, normal, etc...)
  39327. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39328. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39329. * @returns a float array containing vertex data
  39330. */
  39331. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39332. var vertexBuffer = this.getVertexBuffer(kind);
  39333. if (!vertexBuffer) {
  39334. return null;
  39335. }
  39336. var data = vertexBuffer.getData();
  39337. if (!data) {
  39338. return null;
  39339. }
  39340. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39341. var count = this._totalVertices * vertexBuffer.getSize();
  39342. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39343. var copy_1 = new Array(count);
  39344. vertexBuffer.forEach(count, function (value, index) {
  39345. copy_1[index] = value;
  39346. });
  39347. return copy_1;
  39348. }
  39349. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39350. if (data instanceof Array) {
  39351. var offset = vertexBuffer.byteOffset / 4;
  39352. return BABYLON.Tools.Slice(data, offset, offset + count);
  39353. }
  39354. else if (data instanceof ArrayBuffer) {
  39355. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39356. }
  39357. else {
  39358. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39359. }
  39360. }
  39361. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39362. return BABYLON.Tools.Slice(data);
  39363. }
  39364. return data;
  39365. };
  39366. /**
  39367. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39368. * @param kind defines the data kind (Position, normal, etc...)
  39369. * @returns true if the vertex buffer with the specified kind is updatable
  39370. */
  39371. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39372. var vb = this._vertexBuffers[kind];
  39373. if (!vb) {
  39374. return false;
  39375. }
  39376. return vb.isUpdatable();
  39377. };
  39378. /**
  39379. * Gets a specific vertex buffer
  39380. * @param kind defines the data kind (Position, normal, etc...)
  39381. * @returns a {BABYLON.VertexBuffer}
  39382. */
  39383. Geometry.prototype.getVertexBuffer = function (kind) {
  39384. if (!this.isReady()) {
  39385. return null;
  39386. }
  39387. return this._vertexBuffers[kind];
  39388. };
  39389. /**
  39390. * Returns all vertex buffers
  39391. * @return an object holding all vertex buffers indexed by kind
  39392. */
  39393. Geometry.prototype.getVertexBuffers = function () {
  39394. if (!this.isReady()) {
  39395. return null;
  39396. }
  39397. return this._vertexBuffers;
  39398. };
  39399. /**
  39400. * Gets a boolean indicating if specific vertex buffer is present
  39401. * @param kind defines the data kind (Position, normal, etc...)
  39402. * @returns true if data is present
  39403. */
  39404. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39405. if (!this._vertexBuffers) {
  39406. if (this._delayInfo) {
  39407. return this._delayInfo.indexOf(kind) !== -1;
  39408. }
  39409. return false;
  39410. }
  39411. return this._vertexBuffers[kind] !== undefined;
  39412. };
  39413. /**
  39414. * Gets a list of all attached data kinds (Position, normal, etc...)
  39415. * @returns a list of string containing all kinds
  39416. */
  39417. Geometry.prototype.getVerticesDataKinds = function () {
  39418. var result = [];
  39419. var kind;
  39420. if (!this._vertexBuffers && this._delayInfo) {
  39421. for (kind in this._delayInfo) {
  39422. result.push(kind);
  39423. }
  39424. }
  39425. else {
  39426. for (kind in this._vertexBuffers) {
  39427. result.push(kind);
  39428. }
  39429. }
  39430. return result;
  39431. };
  39432. /**
  39433. * Update index buffer
  39434. * @param indices defines the indices to store in the index buffer
  39435. * @param offset defines the offset in the target buffer where to store the data
  39436. */
  39437. Geometry.prototype.updateIndices = function (indices, offset) {
  39438. if (!this._indexBuffer) {
  39439. return;
  39440. }
  39441. if (!this._indexBufferIsUpdatable) {
  39442. this.setIndices(indices, null, true);
  39443. }
  39444. else {
  39445. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39446. }
  39447. };
  39448. /**
  39449. * Creates a new index buffer
  39450. * @param indices defines the indices to store in the index buffer
  39451. * @param totalVertices defines the total number of vertices (could be null)
  39452. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39453. */
  39454. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39455. if (totalVertices === void 0) { totalVertices = null; }
  39456. if (updatable === void 0) { updatable = false; }
  39457. if (this._indexBuffer) {
  39458. this._engine._releaseBuffer(this._indexBuffer);
  39459. }
  39460. this._disposeVertexArrayObjects();
  39461. this._indices = indices;
  39462. this._indexBufferIsUpdatable = updatable;
  39463. if (this._meshes.length !== 0 && this._indices) {
  39464. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39465. }
  39466. if (totalVertices != undefined) { // including null and undefined
  39467. this._totalVertices = totalVertices;
  39468. }
  39469. var meshes = this._meshes;
  39470. var numOfMeshes = meshes.length;
  39471. for (var index = 0; index < numOfMeshes; index++) {
  39472. meshes[index]._createGlobalSubMesh(true);
  39473. }
  39474. this.notifyUpdate();
  39475. };
  39476. /**
  39477. * Return the total number of indices
  39478. * @returns the total number of indices
  39479. */
  39480. Geometry.prototype.getTotalIndices = function () {
  39481. if (!this.isReady()) {
  39482. return 0;
  39483. }
  39484. return this._indices.length;
  39485. };
  39486. /**
  39487. * Gets the index buffer array
  39488. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39489. * @returns the index buffer array
  39490. */
  39491. Geometry.prototype.getIndices = function (copyWhenShared) {
  39492. if (!this.isReady()) {
  39493. return null;
  39494. }
  39495. var orig = this._indices;
  39496. if (!copyWhenShared || this._meshes.length === 1) {
  39497. return orig;
  39498. }
  39499. else {
  39500. var len = orig.length;
  39501. var copy = [];
  39502. for (var i = 0; i < len; i++) {
  39503. copy.push(orig[i]);
  39504. }
  39505. return copy;
  39506. }
  39507. };
  39508. /**
  39509. * Gets the index buffer
  39510. * @return the index buffer
  39511. */
  39512. Geometry.prototype.getIndexBuffer = function () {
  39513. if (!this.isReady()) {
  39514. return null;
  39515. }
  39516. return this._indexBuffer;
  39517. };
  39518. /** @hidden */
  39519. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39520. if (effect === void 0) { effect = null; }
  39521. if (!effect || !this._vertexArrayObjects) {
  39522. return;
  39523. }
  39524. if (this._vertexArrayObjects[effect.key]) {
  39525. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39526. delete this._vertexArrayObjects[effect.key];
  39527. }
  39528. };
  39529. /**
  39530. * Release the associated resources for a specific mesh
  39531. * @param mesh defines the source mesh
  39532. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39533. */
  39534. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39535. var meshes = this._meshes;
  39536. var index = meshes.indexOf(mesh);
  39537. if (index === -1) {
  39538. return;
  39539. }
  39540. meshes.splice(index, 1);
  39541. mesh._geometry = null;
  39542. if (meshes.length === 0 && shouldDispose) {
  39543. this.dispose();
  39544. }
  39545. };
  39546. /**
  39547. * Apply current geometry to a given mesh
  39548. * @param mesh defines the mesh to apply geometry to
  39549. */
  39550. Geometry.prototype.applyToMesh = function (mesh) {
  39551. if (mesh._geometry === this) {
  39552. return;
  39553. }
  39554. var previousGeometry = mesh._geometry;
  39555. if (previousGeometry) {
  39556. previousGeometry.releaseForMesh(mesh);
  39557. }
  39558. var meshes = this._meshes;
  39559. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39560. mesh._geometry = this;
  39561. this._scene.pushGeometry(this);
  39562. meshes.push(mesh);
  39563. if (this.isReady()) {
  39564. this._applyToMesh(mesh);
  39565. }
  39566. else {
  39567. mesh._boundingInfo = this._boundingInfo;
  39568. }
  39569. };
  39570. Geometry.prototype._updateExtend = function (data) {
  39571. if (data === void 0) { data = null; }
  39572. if (!data) {
  39573. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39574. }
  39575. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39576. };
  39577. Geometry.prototype._applyToMesh = function (mesh) {
  39578. var numOfMeshes = this._meshes.length;
  39579. // vertexBuffers
  39580. for (var kind in this._vertexBuffers) {
  39581. if (numOfMeshes === 1) {
  39582. this._vertexBuffers[kind].create();
  39583. }
  39584. var buffer = this._vertexBuffers[kind].getBuffer();
  39585. if (buffer)
  39586. buffer.references = numOfMeshes;
  39587. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39588. if (!this._extend) {
  39589. this._updateExtend();
  39590. }
  39591. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39592. mesh._createGlobalSubMesh(false);
  39593. //bounding info was just created again, world matrix should be applied again.
  39594. mesh._updateBoundingInfo();
  39595. }
  39596. }
  39597. // indexBuffer
  39598. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39599. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39600. }
  39601. if (this._indexBuffer) {
  39602. this._indexBuffer.references = numOfMeshes;
  39603. }
  39604. };
  39605. Geometry.prototype.notifyUpdate = function (kind) {
  39606. if (this.onGeometryUpdated) {
  39607. this.onGeometryUpdated(this, kind);
  39608. }
  39609. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39610. var mesh = _a[_i];
  39611. mesh._markSubMeshesAsAttributesDirty();
  39612. }
  39613. };
  39614. /**
  39615. * Load the geometry if it was flagged as delay loaded
  39616. * @param scene defines the hosting scene
  39617. * @param onLoaded defines a callback called when the geometry is loaded
  39618. */
  39619. Geometry.prototype.load = function (scene, onLoaded) {
  39620. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39621. return;
  39622. }
  39623. if (this.isReady()) {
  39624. if (onLoaded) {
  39625. onLoaded();
  39626. }
  39627. return;
  39628. }
  39629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39630. this._queueLoad(scene, onLoaded);
  39631. };
  39632. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39633. var _this = this;
  39634. if (!this.delayLoadingFile) {
  39635. return;
  39636. }
  39637. scene._addPendingData(this);
  39638. scene._loadFile(this.delayLoadingFile, function (data) {
  39639. if (!_this._delayLoadingFunction) {
  39640. return;
  39641. }
  39642. _this._delayLoadingFunction(JSON.parse(data), _this);
  39643. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39644. _this._delayInfo = [];
  39645. scene._removePendingData(_this);
  39646. var meshes = _this._meshes;
  39647. var numOfMeshes = meshes.length;
  39648. for (var index = 0; index < numOfMeshes; index++) {
  39649. _this._applyToMesh(meshes[index]);
  39650. }
  39651. if (onLoaded) {
  39652. onLoaded();
  39653. }
  39654. }, undefined, true);
  39655. };
  39656. /**
  39657. * Invert the geometry to move from a right handed system to a left handed one.
  39658. */
  39659. Geometry.prototype.toLeftHanded = function () {
  39660. // Flip faces
  39661. var tIndices = this.getIndices(false);
  39662. if (tIndices != null && tIndices.length > 0) {
  39663. for (var i = 0; i < tIndices.length; i += 3) {
  39664. var tTemp = tIndices[i + 0];
  39665. tIndices[i + 0] = tIndices[i + 2];
  39666. tIndices[i + 2] = tTemp;
  39667. }
  39668. this.setIndices(tIndices);
  39669. }
  39670. // Negate position.z
  39671. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39672. if (tPositions != null && tPositions.length > 0) {
  39673. for (var i = 0; i < tPositions.length; i += 3) {
  39674. tPositions[i + 2] = -tPositions[i + 2];
  39675. }
  39676. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39677. }
  39678. // Negate normal.z
  39679. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39680. if (tNormals != null && tNormals.length > 0) {
  39681. for (var i = 0; i < tNormals.length; i += 3) {
  39682. tNormals[i + 2] = -tNormals[i + 2];
  39683. }
  39684. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39685. }
  39686. };
  39687. // Cache
  39688. /** @hidden */
  39689. Geometry.prototype._resetPointsArrayCache = function () {
  39690. this._positions = null;
  39691. };
  39692. /** @hidden */
  39693. Geometry.prototype._generatePointsArray = function () {
  39694. if (this._positions)
  39695. return true;
  39696. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39697. if (!data || data.length === 0) {
  39698. return false;
  39699. }
  39700. this._positions = [];
  39701. for (var index = 0; index < data.length; index += 3) {
  39702. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39703. }
  39704. return true;
  39705. };
  39706. /**
  39707. * Gets a value indicating if the geometry is disposed
  39708. * @returns true if the geometry was disposed
  39709. */
  39710. Geometry.prototype.isDisposed = function () {
  39711. return this._isDisposed;
  39712. };
  39713. Geometry.prototype._disposeVertexArrayObjects = function () {
  39714. if (this._vertexArrayObjects) {
  39715. for (var kind in this._vertexArrayObjects) {
  39716. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39717. }
  39718. this._vertexArrayObjects = {};
  39719. }
  39720. };
  39721. /**
  39722. * Free all associated resources
  39723. */
  39724. Geometry.prototype.dispose = function () {
  39725. var meshes = this._meshes;
  39726. var numOfMeshes = meshes.length;
  39727. var index;
  39728. for (index = 0; index < numOfMeshes; index++) {
  39729. this.releaseForMesh(meshes[index]);
  39730. }
  39731. this._meshes = [];
  39732. this._disposeVertexArrayObjects();
  39733. for (var kind in this._vertexBuffers) {
  39734. this._vertexBuffers[kind].dispose();
  39735. }
  39736. this._vertexBuffers = {};
  39737. this._totalVertices = 0;
  39738. if (this._indexBuffer) {
  39739. this._engine._releaseBuffer(this._indexBuffer);
  39740. }
  39741. this._indexBuffer = null;
  39742. this._indices = [];
  39743. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39744. this.delayLoadingFile = null;
  39745. this._delayLoadingFunction = null;
  39746. this._delayInfo = [];
  39747. this._boundingInfo = null;
  39748. this._scene.removeGeometry(this);
  39749. this._isDisposed = true;
  39750. };
  39751. /**
  39752. * Clone the current geometry into a new geometry
  39753. * @param id defines the unique ID of the new geometry
  39754. * @returns a new geometry object
  39755. */
  39756. Geometry.prototype.copy = function (id) {
  39757. var vertexData = new BABYLON.VertexData();
  39758. vertexData.indices = [];
  39759. var indices = this.getIndices();
  39760. if (indices) {
  39761. for (var index = 0; index < indices.length; index++) {
  39762. vertexData.indices.push(indices[index]);
  39763. }
  39764. }
  39765. var updatable = false;
  39766. var stopChecking = false;
  39767. var kind;
  39768. for (kind in this._vertexBuffers) {
  39769. // using slice() to make a copy of the array and not just reference it
  39770. var data = this.getVerticesData(kind);
  39771. if (data instanceof Float32Array) {
  39772. vertexData.set(new Float32Array(data), kind);
  39773. }
  39774. else {
  39775. vertexData.set(data.slice(0), kind);
  39776. }
  39777. if (!stopChecking) {
  39778. var vb = this.getVertexBuffer(kind);
  39779. if (vb) {
  39780. updatable = vb.isUpdatable();
  39781. stopChecking = !updatable;
  39782. }
  39783. }
  39784. }
  39785. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39786. geometry.delayLoadState = this.delayLoadState;
  39787. geometry.delayLoadingFile = this.delayLoadingFile;
  39788. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39789. for (kind in this._delayInfo) {
  39790. geometry._delayInfo = geometry._delayInfo || [];
  39791. geometry._delayInfo.push(kind);
  39792. }
  39793. // Bounding info
  39794. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39795. return geometry;
  39796. };
  39797. /**
  39798. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39799. * @return a JSON representation of the current geometry data (without the vertices data)
  39800. */
  39801. Geometry.prototype.serialize = function () {
  39802. var serializationObject = {};
  39803. serializationObject.id = this.id;
  39804. serializationObject.updatable = this._updatable;
  39805. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39806. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39807. }
  39808. return serializationObject;
  39809. };
  39810. Geometry.prototype.toNumberArray = function (origin) {
  39811. if (Array.isArray(origin)) {
  39812. return origin;
  39813. }
  39814. else {
  39815. return Array.prototype.slice.call(origin);
  39816. }
  39817. };
  39818. /**
  39819. * Serialize all vertices data into a JSON oject
  39820. * @returns a JSON representation of the current geometry data
  39821. */
  39822. Geometry.prototype.serializeVerticeData = function () {
  39823. var serializationObject = this.serialize();
  39824. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39825. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39826. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39827. serializationObject.positions._updatable = true;
  39828. }
  39829. }
  39830. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39831. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39832. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39833. serializationObject.normals._updatable = true;
  39834. }
  39835. }
  39836. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39837. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39838. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39839. serializationObject.tangets._updatable = true;
  39840. }
  39841. }
  39842. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39843. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39844. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39845. serializationObject.uvs._updatable = true;
  39846. }
  39847. }
  39848. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39849. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39850. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39851. serializationObject.uv2s._updatable = true;
  39852. }
  39853. }
  39854. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39855. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39856. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39857. serializationObject.uv3s._updatable = true;
  39858. }
  39859. }
  39860. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39861. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39862. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39863. serializationObject.uv4s._updatable = true;
  39864. }
  39865. }
  39866. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39867. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39868. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39869. serializationObject.uv5s._updatable = true;
  39870. }
  39871. }
  39872. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39873. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39874. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39875. serializationObject.uv6s._updatable = true;
  39876. }
  39877. }
  39878. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39879. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39880. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39881. serializationObject.colors._updatable = true;
  39882. }
  39883. }
  39884. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39885. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39886. serializationObject.matricesIndices._isExpanded = true;
  39887. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39888. serializationObject.matricesIndices._updatable = true;
  39889. }
  39890. }
  39891. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39892. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39893. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39894. serializationObject.matricesWeights._updatable = true;
  39895. }
  39896. }
  39897. serializationObject.indices = this.toNumberArray(this.getIndices());
  39898. return serializationObject;
  39899. };
  39900. // Statics
  39901. /**
  39902. * Extracts a clone of a mesh geometry
  39903. * @param mesh defines the source mesh
  39904. * @param id defines the unique ID of the new geometry object
  39905. * @returns the new geometry object
  39906. */
  39907. Geometry.ExtractFromMesh = function (mesh, id) {
  39908. var geometry = mesh._geometry;
  39909. if (!geometry) {
  39910. return null;
  39911. }
  39912. return geometry.copy(id);
  39913. };
  39914. /**
  39915. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39916. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39917. * Be aware Math.random() could cause collisions, but:
  39918. * "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"
  39919. * @returns a string containing a new GUID
  39920. */
  39921. Geometry.RandomId = function () {
  39922. return BABYLON.Tools.RandomId();
  39923. };
  39924. /** @hidden */
  39925. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39926. var scene = mesh.getScene();
  39927. // Geometry
  39928. var geometryId = parsedGeometry.geometryId;
  39929. if (geometryId) {
  39930. var geometry = scene.getGeometryByID(geometryId);
  39931. if (geometry) {
  39932. geometry.applyToMesh(mesh);
  39933. }
  39934. }
  39935. else if (parsedGeometry instanceof ArrayBuffer) {
  39936. var binaryInfo = mesh._binaryInfo;
  39937. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39938. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39939. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39940. }
  39941. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39942. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39943. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39944. }
  39945. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39946. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39947. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39948. }
  39949. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39950. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39951. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39952. }
  39953. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39954. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39955. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39956. }
  39957. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39958. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39959. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39960. }
  39961. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39962. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39963. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39964. }
  39965. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39966. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39967. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39968. }
  39969. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39970. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39971. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39972. }
  39973. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39974. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39975. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39976. }
  39977. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39978. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39979. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39980. }
  39981. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39982. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39983. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39984. }
  39985. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39986. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39987. mesh.setIndices(indicesData, null);
  39988. }
  39989. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39990. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39991. mesh.subMeshes = [];
  39992. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39993. var materialIndex = subMeshesData[(i * 5) + 0];
  39994. var verticesStart = subMeshesData[(i * 5) + 1];
  39995. var verticesCount = subMeshesData[(i * 5) + 2];
  39996. var indexStart = subMeshesData[(i * 5) + 3];
  39997. var indexCount = subMeshesData[(i * 5) + 4];
  39998. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39999. }
  40000. }
  40001. }
  40002. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40003. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40004. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40005. if (parsedGeometry.tangents) {
  40006. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40007. }
  40008. if (parsedGeometry.uvs) {
  40009. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40010. }
  40011. if (parsedGeometry.uvs2) {
  40012. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40013. }
  40014. if (parsedGeometry.uvs3) {
  40015. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40016. }
  40017. if (parsedGeometry.uvs4) {
  40018. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40019. }
  40020. if (parsedGeometry.uvs5) {
  40021. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40022. }
  40023. if (parsedGeometry.uvs6) {
  40024. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40025. }
  40026. if (parsedGeometry.colors) {
  40027. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40028. }
  40029. if (parsedGeometry.matricesIndices) {
  40030. if (!parsedGeometry.matricesIndices._isExpanded) {
  40031. var floatIndices = [];
  40032. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40033. var matricesIndex = parsedGeometry.matricesIndices[i];
  40034. floatIndices.push(matricesIndex & 0x000000FF);
  40035. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40036. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40037. floatIndices.push(matricesIndex >> 24);
  40038. }
  40039. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40040. }
  40041. else {
  40042. delete parsedGeometry.matricesIndices._isExpanded;
  40043. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40044. }
  40045. }
  40046. if (parsedGeometry.matricesIndicesExtra) {
  40047. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40048. var floatIndices = [];
  40049. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40050. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40051. floatIndices.push(matricesIndex & 0x000000FF);
  40052. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40053. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40054. floatIndices.push(matricesIndex >> 24);
  40055. }
  40056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40057. }
  40058. else {
  40059. delete parsedGeometry.matricesIndices._isExpanded;
  40060. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40061. }
  40062. }
  40063. if (parsedGeometry.matricesWeights) {
  40064. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40065. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40066. }
  40067. if (parsedGeometry.matricesWeightsExtra) {
  40068. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40069. }
  40070. mesh.setIndices(parsedGeometry.indices, null);
  40071. }
  40072. // SubMeshes
  40073. if (parsedGeometry.subMeshes) {
  40074. mesh.subMeshes = [];
  40075. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40076. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40077. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40078. }
  40079. }
  40080. // Flat shading
  40081. if (mesh._shouldGenerateFlatShading) {
  40082. mesh.convertToFlatShadedMesh();
  40083. delete mesh._shouldGenerateFlatShading;
  40084. }
  40085. // Update
  40086. mesh.computeWorldMatrix(true);
  40087. // Octree
  40088. var sceneOctree = scene.selectionOctree;
  40089. if (sceneOctree !== undefined && sceneOctree !== null) {
  40090. sceneOctree.addMesh(mesh);
  40091. }
  40092. };
  40093. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40094. var epsilon = 1e-3;
  40095. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40096. return;
  40097. }
  40098. var noInfluenceBoneIndex = 0.0;
  40099. if (parsedGeometry.skeletonId > -1) {
  40100. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40101. if (!skeleton) {
  40102. return;
  40103. }
  40104. noInfluenceBoneIndex = skeleton.bones.length;
  40105. }
  40106. else {
  40107. return;
  40108. }
  40109. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40110. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40111. var matricesWeights = parsedGeometry.matricesWeights;
  40112. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40113. var influencers = parsedGeometry.numBoneInfluencer;
  40114. var size = matricesWeights.length;
  40115. for (var i = 0; i < size; i += 4) {
  40116. var weight = 0.0;
  40117. var firstZeroWeight = -1;
  40118. for (var j = 0; j < 4; j++) {
  40119. var w = matricesWeights[i + j];
  40120. weight += w;
  40121. if (w < epsilon && firstZeroWeight < 0) {
  40122. firstZeroWeight = j;
  40123. }
  40124. }
  40125. if (matricesWeightsExtra) {
  40126. for (var j = 0; j < 4; j++) {
  40127. var w = matricesWeightsExtra[i + j];
  40128. weight += w;
  40129. if (w < epsilon && firstZeroWeight < 0) {
  40130. firstZeroWeight = j + 4;
  40131. }
  40132. }
  40133. }
  40134. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40135. firstZeroWeight = influencers - 1;
  40136. }
  40137. if (weight > epsilon) {
  40138. var mweight = 1.0 / weight;
  40139. for (var j = 0; j < 4; j++) {
  40140. matricesWeights[i + j] *= mweight;
  40141. }
  40142. if (matricesWeightsExtra) {
  40143. for (var j = 0; j < 4; j++) {
  40144. matricesWeightsExtra[i + j] *= mweight;
  40145. }
  40146. }
  40147. }
  40148. else {
  40149. if (firstZeroWeight >= 4) {
  40150. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40151. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40152. }
  40153. else {
  40154. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40155. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40156. }
  40157. }
  40158. }
  40159. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40160. if (parsedGeometry.matricesWeightsExtra) {
  40161. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40162. }
  40163. };
  40164. /**
  40165. * Create a new geometry from persisted data (Using .babylon file format)
  40166. * @param parsedVertexData defines the persisted data
  40167. * @param scene defines the hosting scene
  40168. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40169. * @returns the new geometry object
  40170. */
  40171. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40172. if (scene.getGeometryByID(parsedVertexData.id)) {
  40173. return null; // null since geometry could be something else than a box...
  40174. }
  40175. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40176. if (BABYLON.Tags) {
  40177. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40178. }
  40179. if (parsedVertexData.delayLoadingFile) {
  40180. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40181. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40182. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40183. geometry._delayInfo = [];
  40184. if (parsedVertexData.hasUVs) {
  40185. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40186. }
  40187. if (parsedVertexData.hasUVs2) {
  40188. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40189. }
  40190. if (parsedVertexData.hasUVs3) {
  40191. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40192. }
  40193. if (parsedVertexData.hasUVs4) {
  40194. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40195. }
  40196. if (parsedVertexData.hasUVs5) {
  40197. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40198. }
  40199. if (parsedVertexData.hasUVs6) {
  40200. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40201. }
  40202. if (parsedVertexData.hasColors) {
  40203. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40204. }
  40205. if (parsedVertexData.hasMatricesIndices) {
  40206. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40207. }
  40208. if (parsedVertexData.hasMatricesWeights) {
  40209. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40210. }
  40211. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40212. }
  40213. else {
  40214. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40215. }
  40216. scene.pushGeometry(geometry, true);
  40217. return geometry;
  40218. };
  40219. return Geometry;
  40220. }());
  40221. BABYLON.Geometry = Geometry;
  40222. // Primitives
  40223. /// Abstract class
  40224. /**
  40225. * Abstract class used to provide common services for all typed geometries
  40226. * @hidden
  40227. */
  40228. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40229. __extends(_PrimitiveGeometry, _super);
  40230. /**
  40231. * Creates a new typed geometry
  40232. * @param id defines the unique ID of the geometry
  40233. * @param scene defines the hosting scene
  40234. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40235. * @param mesh defines the hosting mesh (can be null)
  40236. */
  40237. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40238. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40239. if (mesh === void 0) { mesh = null; }
  40240. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40241. _this._canBeRegenerated = _canBeRegenerated;
  40242. _this._beingRegenerated = true;
  40243. _this.regenerate();
  40244. _this._beingRegenerated = false;
  40245. return _this;
  40246. }
  40247. /**
  40248. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40249. * @returns true if the geometry can be regenerated
  40250. */
  40251. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40252. return this._canBeRegenerated;
  40253. };
  40254. /**
  40255. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40256. */
  40257. _PrimitiveGeometry.prototype.regenerate = function () {
  40258. if (!this._canBeRegenerated) {
  40259. return;
  40260. }
  40261. this._beingRegenerated = true;
  40262. this.setAllVerticesData(this._regenerateVertexData(), false);
  40263. this._beingRegenerated = false;
  40264. };
  40265. /**
  40266. * Clone the geometry
  40267. * @param id defines the unique ID of the new geometry
  40268. * @returns the new geometry
  40269. */
  40270. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40271. return _super.prototype.copy.call(this, id);
  40272. };
  40273. // overrides
  40274. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40275. if (!this._beingRegenerated) {
  40276. return;
  40277. }
  40278. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40279. };
  40280. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40281. if (!this._beingRegenerated) {
  40282. return;
  40283. }
  40284. _super.prototype.setVerticesData.call(this, kind, data, false);
  40285. };
  40286. // to override
  40287. /** @hidden */
  40288. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40289. throw new Error("Abstract method");
  40290. };
  40291. _PrimitiveGeometry.prototype.copy = function (id) {
  40292. throw new Error("Must be overriden in sub-classes.");
  40293. };
  40294. _PrimitiveGeometry.prototype.serialize = function () {
  40295. var serializationObject = _super.prototype.serialize.call(this);
  40296. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40297. return serializationObject;
  40298. };
  40299. return _PrimitiveGeometry;
  40300. }(Geometry));
  40301. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40302. /**
  40303. * Creates a ribbon geometry
  40304. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40305. */
  40306. var RibbonGeometry = /** @class */ (function (_super) {
  40307. __extends(RibbonGeometry, _super);
  40308. /**
  40309. * Creates a ribbon geometry
  40310. * @param id defines the unique ID of the geometry
  40311. * @param scene defines the hosting scene
  40312. * @param pathArray defines the array of paths to use
  40313. * @param closeArray defines if the last path and the first path must be joined
  40314. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40315. * @param offset defines the offset between points
  40316. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40317. * @param mesh defines the hosting mesh (can be null)
  40318. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40319. */
  40320. function RibbonGeometry(id, scene,
  40321. /**
  40322. * Defines the array of paths to use
  40323. */
  40324. pathArray,
  40325. /**
  40326. * Defines if the last and first points of each path in your pathArray must be joined
  40327. */
  40328. closeArray,
  40329. /**
  40330. * Defines if the last and first points of each path in your pathArray must be joined
  40331. */
  40332. closePath,
  40333. /**
  40334. * Defines the offset between points
  40335. */
  40336. offset, canBeRegenerated, mesh,
  40337. /**
  40338. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40339. */
  40340. side) {
  40341. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40342. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40343. _this.pathArray = pathArray;
  40344. _this.closeArray = closeArray;
  40345. _this.closePath = closePath;
  40346. _this.offset = offset;
  40347. _this.side = side;
  40348. return _this;
  40349. }
  40350. /** @hidden */
  40351. RibbonGeometry.prototype._regenerateVertexData = function () {
  40352. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40353. };
  40354. RibbonGeometry.prototype.copy = function (id) {
  40355. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40356. };
  40357. return RibbonGeometry;
  40358. }(_PrimitiveGeometry));
  40359. BABYLON.RibbonGeometry = RibbonGeometry;
  40360. /**
  40361. * Creates a box geometry
  40362. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40363. */
  40364. var BoxGeometry = /** @class */ (function (_super) {
  40365. __extends(BoxGeometry, _super);
  40366. /**
  40367. * Creates a box geometry
  40368. * @param id defines the unique ID of the geometry
  40369. * @param scene defines the hosting scene
  40370. * @param size defines the zise of the box (width, height and depth are the same)
  40371. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40372. * @param mesh defines the hosting mesh (can be null)
  40373. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40374. */
  40375. function BoxGeometry(id, scene,
  40376. /**
  40377. * Defines the zise of the box (width, height and depth are the same)
  40378. */
  40379. size, canBeRegenerated, mesh,
  40380. /**
  40381. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40382. */
  40383. side) {
  40384. if (mesh === void 0) { mesh = null; }
  40385. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40386. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40387. _this.size = size;
  40388. _this.side = side;
  40389. return _this;
  40390. }
  40391. BoxGeometry.prototype._regenerateVertexData = function () {
  40392. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40393. };
  40394. BoxGeometry.prototype.copy = function (id) {
  40395. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40396. };
  40397. BoxGeometry.prototype.serialize = function () {
  40398. var serializationObject = _super.prototype.serialize.call(this);
  40399. serializationObject.size = this.size;
  40400. return serializationObject;
  40401. };
  40402. BoxGeometry.Parse = function (parsedBox, scene) {
  40403. if (scene.getGeometryByID(parsedBox.id)) {
  40404. return null; // null since geometry could be something else than a box...
  40405. }
  40406. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40407. if (BABYLON.Tags) {
  40408. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40409. }
  40410. scene.pushGeometry(box, true);
  40411. return box;
  40412. };
  40413. return BoxGeometry;
  40414. }(_PrimitiveGeometry));
  40415. BABYLON.BoxGeometry = BoxGeometry;
  40416. /**
  40417. * Creates a sphere geometry
  40418. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40419. */
  40420. var SphereGeometry = /** @class */ (function (_super) {
  40421. __extends(SphereGeometry, _super);
  40422. /**
  40423. * Create a new sphere geometry
  40424. * @param id defines the unique ID of the geometry
  40425. * @param scene defines the hosting scene
  40426. * @param segments defines the number of segments to use to create the sphere
  40427. * @param diameter defines the diameter of the sphere
  40428. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40429. * @param mesh defines the hosting mesh (can be null)
  40430. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40431. */
  40432. function SphereGeometry(id, scene,
  40433. /**
  40434. * Defines the number of segments to use to create the sphere
  40435. */
  40436. segments,
  40437. /**
  40438. * Defines the diameter of the sphere
  40439. */
  40440. diameter, canBeRegenerated, mesh,
  40441. /**
  40442. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40443. */
  40444. side) {
  40445. if (mesh === void 0) { mesh = null; }
  40446. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40447. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40448. _this.segments = segments;
  40449. _this.diameter = diameter;
  40450. _this.side = side;
  40451. return _this;
  40452. }
  40453. SphereGeometry.prototype._regenerateVertexData = function () {
  40454. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40455. };
  40456. SphereGeometry.prototype.copy = function (id) {
  40457. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40458. };
  40459. SphereGeometry.prototype.serialize = function () {
  40460. var serializationObject = _super.prototype.serialize.call(this);
  40461. serializationObject.segments = this.segments;
  40462. serializationObject.diameter = this.diameter;
  40463. return serializationObject;
  40464. };
  40465. SphereGeometry.Parse = function (parsedSphere, scene) {
  40466. if (scene.getGeometryByID(parsedSphere.id)) {
  40467. return null; // null since geometry could be something else than a sphere...
  40468. }
  40469. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40470. if (BABYLON.Tags) {
  40471. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40472. }
  40473. scene.pushGeometry(sphere, true);
  40474. return sphere;
  40475. };
  40476. return SphereGeometry;
  40477. }(_PrimitiveGeometry));
  40478. BABYLON.SphereGeometry = SphereGeometry;
  40479. /**
  40480. * Creates a disc geometry
  40481. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40482. */
  40483. var DiscGeometry = /** @class */ (function (_super) {
  40484. __extends(DiscGeometry, _super);
  40485. /**
  40486. * Creates a new disc geometry
  40487. * @param id defines the unique ID of the geometry
  40488. * @param scene defines the hosting scene
  40489. * @param radius defines the radius of the disc
  40490. * @param tessellation defines the tesselation factor to apply to the disc
  40491. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40492. * @param mesh defines the hosting mesh (can be null)
  40493. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40494. */
  40495. function DiscGeometry(id, scene,
  40496. /**
  40497. * Defines the radius of the disc
  40498. */
  40499. radius,
  40500. /**
  40501. * Defines the tesselation factor to apply to the disc
  40502. */
  40503. tessellation, canBeRegenerated, mesh,
  40504. /**
  40505. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40506. */
  40507. side) {
  40508. if (mesh === void 0) { mesh = null; }
  40509. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40510. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40511. _this.radius = radius;
  40512. _this.tessellation = tessellation;
  40513. _this.side = side;
  40514. return _this;
  40515. }
  40516. DiscGeometry.prototype._regenerateVertexData = function () {
  40517. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40518. };
  40519. DiscGeometry.prototype.copy = function (id) {
  40520. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40521. };
  40522. return DiscGeometry;
  40523. }(_PrimitiveGeometry));
  40524. BABYLON.DiscGeometry = DiscGeometry;
  40525. /**
  40526. * Creates a new cylinder geometry
  40527. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40528. */
  40529. var CylinderGeometry = /** @class */ (function (_super) {
  40530. __extends(CylinderGeometry, _super);
  40531. /**
  40532. * Creates a new cylinder geometry
  40533. * @param id defines the unique ID of the geometry
  40534. * @param scene defines the hosting scene
  40535. * @param height defines the height of the cylinder
  40536. * @param diameterTop defines the diameter of the cylinder's top cap
  40537. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40538. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40539. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40540. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40541. * @param mesh defines the hosting mesh (can be null)
  40542. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40543. */
  40544. function CylinderGeometry(id, scene,
  40545. /**
  40546. * Defines the height of the cylinder
  40547. */
  40548. height,
  40549. /**
  40550. * Defines the diameter of the cylinder's top cap
  40551. */
  40552. diameterTop,
  40553. /**
  40554. * Defines the diameter of the cylinder's bottom cap
  40555. */
  40556. diameterBottom,
  40557. /**
  40558. * Defines the tessellation factor to apply to the cylinder
  40559. */
  40560. tessellation,
  40561. /**
  40562. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40563. */
  40564. subdivisions, canBeRegenerated, mesh,
  40565. /**
  40566. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40567. */
  40568. side) {
  40569. if (subdivisions === void 0) { subdivisions = 1; }
  40570. if (mesh === void 0) { mesh = null; }
  40571. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40572. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40573. _this.height = height;
  40574. _this.diameterTop = diameterTop;
  40575. _this.diameterBottom = diameterBottom;
  40576. _this.tessellation = tessellation;
  40577. _this.subdivisions = subdivisions;
  40578. _this.side = side;
  40579. return _this;
  40580. }
  40581. CylinderGeometry.prototype._regenerateVertexData = function () {
  40582. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40583. };
  40584. CylinderGeometry.prototype.copy = function (id) {
  40585. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40586. };
  40587. CylinderGeometry.prototype.serialize = function () {
  40588. var serializationObject = _super.prototype.serialize.call(this);
  40589. serializationObject.height = this.height;
  40590. serializationObject.diameterTop = this.diameterTop;
  40591. serializationObject.diameterBottom = this.diameterBottom;
  40592. serializationObject.tessellation = this.tessellation;
  40593. return serializationObject;
  40594. };
  40595. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40596. if (scene.getGeometryByID(parsedCylinder.id)) {
  40597. return null; // null since geometry could be something else than a cylinder...
  40598. }
  40599. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40600. if (BABYLON.Tags) {
  40601. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40602. }
  40603. scene.pushGeometry(cylinder, true);
  40604. return cylinder;
  40605. };
  40606. return CylinderGeometry;
  40607. }(_PrimitiveGeometry));
  40608. BABYLON.CylinderGeometry = CylinderGeometry;
  40609. /**
  40610. * Creates a new torus geometry
  40611. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40612. */
  40613. var TorusGeometry = /** @class */ (function (_super) {
  40614. __extends(TorusGeometry, _super);
  40615. /**
  40616. * Creates a new torus geometry
  40617. * @param id defines the unique ID of the geometry
  40618. * @param scene defines the hosting scene
  40619. * @param diameter defines the diameter of the torus
  40620. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40621. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40622. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40623. * @param mesh defines the hosting mesh (can be null)
  40624. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40625. */
  40626. function TorusGeometry(id, scene,
  40627. /**
  40628. * Defines the diameter of the torus
  40629. */
  40630. diameter,
  40631. /**
  40632. * Defines the thickness of the torus (ie. internal diameter)
  40633. */
  40634. thickness,
  40635. /**
  40636. * Defines the tesselation factor to apply to the torus
  40637. */
  40638. tessellation, canBeRegenerated, mesh,
  40639. /**
  40640. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40641. */
  40642. side) {
  40643. if (mesh === void 0) { mesh = null; }
  40644. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40645. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40646. _this.diameter = diameter;
  40647. _this.thickness = thickness;
  40648. _this.tessellation = tessellation;
  40649. _this.side = side;
  40650. return _this;
  40651. }
  40652. TorusGeometry.prototype._regenerateVertexData = function () {
  40653. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40654. };
  40655. TorusGeometry.prototype.copy = function (id) {
  40656. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40657. };
  40658. TorusGeometry.prototype.serialize = function () {
  40659. var serializationObject = _super.prototype.serialize.call(this);
  40660. serializationObject.diameter = this.diameter;
  40661. serializationObject.thickness = this.thickness;
  40662. serializationObject.tessellation = this.tessellation;
  40663. return serializationObject;
  40664. };
  40665. TorusGeometry.Parse = function (parsedTorus, scene) {
  40666. if (scene.getGeometryByID(parsedTorus.id)) {
  40667. return null; // null since geometry could be something else than a torus...
  40668. }
  40669. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40670. if (BABYLON.Tags) {
  40671. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40672. }
  40673. scene.pushGeometry(torus, true);
  40674. return torus;
  40675. };
  40676. return TorusGeometry;
  40677. }(_PrimitiveGeometry));
  40678. BABYLON.TorusGeometry = TorusGeometry;
  40679. /**
  40680. * Creates a new ground geometry
  40681. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40682. */
  40683. var GroundGeometry = /** @class */ (function (_super) {
  40684. __extends(GroundGeometry, _super);
  40685. /**
  40686. * Creates a new ground geometry
  40687. * @param id defines the unique ID of the geometry
  40688. * @param scene defines the hosting scene
  40689. * @param width defines the width of the ground
  40690. * @param height defines the height of the ground
  40691. * @param subdivisions defines the subdivisions to apply to the ground
  40692. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40693. * @param mesh defines the hosting mesh (can be null)
  40694. */
  40695. function GroundGeometry(id, scene,
  40696. /**
  40697. * Defines the width of the ground
  40698. */
  40699. width,
  40700. /**
  40701. * Defines the height of the ground
  40702. */
  40703. height,
  40704. /**
  40705. * Defines the subdivisions to apply to the ground
  40706. */
  40707. subdivisions, canBeRegenerated, mesh) {
  40708. if (mesh === void 0) { mesh = null; }
  40709. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40710. _this.width = width;
  40711. _this.height = height;
  40712. _this.subdivisions = subdivisions;
  40713. return _this;
  40714. }
  40715. GroundGeometry.prototype._regenerateVertexData = function () {
  40716. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40717. };
  40718. GroundGeometry.prototype.copy = function (id) {
  40719. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40720. };
  40721. GroundGeometry.prototype.serialize = function () {
  40722. var serializationObject = _super.prototype.serialize.call(this);
  40723. serializationObject.width = this.width;
  40724. serializationObject.height = this.height;
  40725. serializationObject.subdivisions = this.subdivisions;
  40726. return serializationObject;
  40727. };
  40728. GroundGeometry.Parse = function (parsedGround, scene) {
  40729. if (scene.getGeometryByID(parsedGround.id)) {
  40730. return null; // null since geometry could be something else than a ground...
  40731. }
  40732. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40733. if (BABYLON.Tags) {
  40734. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40735. }
  40736. scene.pushGeometry(ground, true);
  40737. return ground;
  40738. };
  40739. return GroundGeometry;
  40740. }(_PrimitiveGeometry));
  40741. BABYLON.GroundGeometry = GroundGeometry;
  40742. /**
  40743. * Creates a tiled ground geometry
  40744. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40745. */
  40746. var TiledGroundGeometry = /** @class */ (function (_super) {
  40747. __extends(TiledGroundGeometry, _super);
  40748. /**
  40749. * Creates a tiled ground geometry
  40750. * @param id defines the unique ID of the geometry
  40751. * @param scene defines the hosting scene
  40752. * @param xmin defines the minimum value on X axis
  40753. * @param zmin defines the minimum value on Z axis
  40754. * @param xmax defines the maximum value on X axis
  40755. * @param zmax defines the maximum value on Z axis
  40756. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40757. * @param precision defines the precision to use when computing the tiles
  40758. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40759. * @param mesh defines the hosting mesh (can be null)
  40760. */
  40761. function TiledGroundGeometry(id, scene,
  40762. /**
  40763. * Defines the minimum value on X axis
  40764. */
  40765. xmin,
  40766. /**
  40767. * Defines the minimum value on Z axis
  40768. */
  40769. zmin,
  40770. /**
  40771. * Defines the maximum value on X axis
  40772. */
  40773. xmax,
  40774. /**
  40775. * Defines the maximum value on Z axis
  40776. */
  40777. zmax,
  40778. /**
  40779. * Defines the subdivisions to apply to the ground
  40780. */
  40781. subdivisions,
  40782. /**
  40783. * Defines the precision to use when computing the tiles
  40784. */
  40785. precision, canBeRegenerated, mesh) {
  40786. if (mesh === void 0) { mesh = null; }
  40787. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40788. _this.xmin = xmin;
  40789. _this.zmin = zmin;
  40790. _this.xmax = xmax;
  40791. _this.zmax = zmax;
  40792. _this.subdivisions = subdivisions;
  40793. _this.precision = precision;
  40794. return _this;
  40795. }
  40796. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40797. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40798. };
  40799. TiledGroundGeometry.prototype.copy = function (id) {
  40800. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40801. };
  40802. return TiledGroundGeometry;
  40803. }(_PrimitiveGeometry));
  40804. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40805. /**
  40806. * Creates a plane geometry
  40807. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40808. */
  40809. var PlaneGeometry = /** @class */ (function (_super) {
  40810. __extends(PlaneGeometry, _super);
  40811. /**
  40812. * Creates a plane geometry
  40813. * @param id defines the unique ID of the geometry
  40814. * @param scene defines the hosting scene
  40815. * @param size defines the size of the plane (width === height)
  40816. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40817. * @param mesh defines the hosting mesh (can be null)
  40818. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40819. */
  40820. function PlaneGeometry(id, scene,
  40821. /**
  40822. * Defines the size of the plane (width === height)
  40823. */
  40824. size, canBeRegenerated, mesh,
  40825. /**
  40826. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40827. */
  40828. side) {
  40829. if (mesh === void 0) { mesh = null; }
  40830. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40831. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40832. _this.size = size;
  40833. _this.side = side;
  40834. return _this;
  40835. }
  40836. PlaneGeometry.prototype._regenerateVertexData = function () {
  40837. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40838. };
  40839. PlaneGeometry.prototype.copy = function (id) {
  40840. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40841. };
  40842. PlaneGeometry.prototype.serialize = function () {
  40843. var serializationObject = _super.prototype.serialize.call(this);
  40844. serializationObject.size = this.size;
  40845. return serializationObject;
  40846. };
  40847. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40848. if (scene.getGeometryByID(parsedPlane.id)) {
  40849. return null; // null since geometry could be something else than a ground...
  40850. }
  40851. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40852. if (BABYLON.Tags) {
  40853. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40854. }
  40855. scene.pushGeometry(plane, true);
  40856. return plane;
  40857. };
  40858. return PlaneGeometry;
  40859. }(_PrimitiveGeometry));
  40860. BABYLON.PlaneGeometry = PlaneGeometry;
  40861. /**
  40862. * Creates a torus knot geometry
  40863. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40864. */
  40865. var TorusKnotGeometry = /** @class */ (function (_super) {
  40866. __extends(TorusKnotGeometry, _super);
  40867. /**
  40868. * Creates a torus knot geometry
  40869. * @param id defines the unique ID of the geometry
  40870. * @param scene defines the hosting scene
  40871. * @param radius defines the radius of the torus knot
  40872. * @param tube defines the thickness of the torus knot tube
  40873. * @param radialSegments defines the number of radial segments
  40874. * @param tubularSegments defines the number of tubular segments
  40875. * @param p defines the first number of windings
  40876. * @param q defines the second number of windings
  40877. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40878. * @param mesh defines the hosting mesh (can be null)
  40879. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40880. */
  40881. function TorusKnotGeometry(id, scene,
  40882. /**
  40883. * Defines the radius of the torus knot
  40884. */
  40885. radius,
  40886. /**
  40887. * Defines the thickness of the torus knot tube
  40888. */
  40889. tube,
  40890. /**
  40891. * Defines the number of radial segments
  40892. */
  40893. radialSegments,
  40894. /**
  40895. * Defines the number of tubular segments
  40896. */
  40897. tubularSegments,
  40898. /**
  40899. * Defines the first number of windings
  40900. */
  40901. p,
  40902. /**
  40903. * Defines the second number of windings
  40904. */
  40905. q, canBeRegenerated, mesh,
  40906. /**
  40907. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40908. */
  40909. side) {
  40910. if (mesh === void 0) { mesh = null; }
  40911. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40912. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40913. _this.radius = radius;
  40914. _this.tube = tube;
  40915. _this.radialSegments = radialSegments;
  40916. _this.tubularSegments = tubularSegments;
  40917. _this.p = p;
  40918. _this.q = q;
  40919. _this.side = side;
  40920. return _this;
  40921. }
  40922. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40923. 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 });
  40924. };
  40925. TorusKnotGeometry.prototype.copy = function (id) {
  40926. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40927. };
  40928. TorusKnotGeometry.prototype.serialize = function () {
  40929. var serializationObject = _super.prototype.serialize.call(this);
  40930. serializationObject.radius = this.radius;
  40931. serializationObject.tube = this.tube;
  40932. serializationObject.radialSegments = this.radialSegments;
  40933. serializationObject.tubularSegments = this.tubularSegments;
  40934. serializationObject.p = this.p;
  40935. serializationObject.q = this.q;
  40936. return serializationObject;
  40937. };
  40938. ;
  40939. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40940. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40941. return null; // null since geometry could be something else than a ground...
  40942. }
  40943. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40944. if (BABYLON.Tags) {
  40945. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40946. }
  40947. scene.pushGeometry(torusKnot, true);
  40948. return torusKnot;
  40949. };
  40950. return TorusKnotGeometry;
  40951. }(_PrimitiveGeometry));
  40952. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40953. //}
  40954. })(BABYLON || (BABYLON = {}));
  40955. //# sourceMappingURL=babylon.geometry.js.map
  40956. var BABYLON;
  40957. (function (BABYLON) {
  40958. /**
  40959. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40960. */
  40961. var PerformanceMonitor = /** @class */ (function () {
  40962. /**
  40963. * constructor
  40964. * @param frameSampleSize The number of samples required to saturate the sliding window
  40965. */
  40966. function PerformanceMonitor(frameSampleSize) {
  40967. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40968. this._enabled = true;
  40969. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40970. }
  40971. /**
  40972. * Samples current frame
  40973. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40974. */
  40975. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40976. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40977. if (!this._enabled)
  40978. return;
  40979. if (this._lastFrameTimeMs != null) {
  40980. var dt = timeMs - this._lastFrameTimeMs;
  40981. this._rollingFrameTime.add(dt);
  40982. }
  40983. this._lastFrameTimeMs = timeMs;
  40984. };
  40985. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40986. /**
  40987. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40988. * @return Average frame time in milliseconds
  40989. */
  40990. get: function () {
  40991. return this._rollingFrameTime.average;
  40992. },
  40993. enumerable: true,
  40994. configurable: true
  40995. });
  40996. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40997. /**
  40998. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40999. * @return Frame time variance in milliseconds squared
  41000. */
  41001. get: function () {
  41002. return this._rollingFrameTime.variance;
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41008. /**
  41009. * Returns the frame time of the most recent frame
  41010. * @return Frame time in milliseconds
  41011. */
  41012. get: function () {
  41013. return this._rollingFrameTime.history(0);
  41014. },
  41015. enumerable: true,
  41016. configurable: true
  41017. });
  41018. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41019. /**
  41020. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41021. * @return Framerate in frames per second
  41022. */
  41023. get: function () {
  41024. return 1000.0 / this._rollingFrameTime.average;
  41025. },
  41026. enumerable: true,
  41027. configurable: true
  41028. });
  41029. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41030. /**
  41031. * Returns the average framerate in frames per second using the most recent frame time
  41032. * @return Framerate in frames per second
  41033. */
  41034. get: function () {
  41035. var history = this._rollingFrameTime.history(0);
  41036. if (history === 0) {
  41037. return 0;
  41038. }
  41039. return 1000.0 / history;
  41040. },
  41041. enumerable: true,
  41042. configurable: true
  41043. });
  41044. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41045. /**
  41046. * Returns true if enough samples have been taken to completely fill the sliding window
  41047. * @return true if saturated
  41048. */
  41049. get: function () {
  41050. return this._rollingFrameTime.isSaturated();
  41051. },
  41052. enumerable: true,
  41053. configurable: true
  41054. });
  41055. /**
  41056. * Enables contributions to the sliding window sample set
  41057. */
  41058. PerformanceMonitor.prototype.enable = function () {
  41059. this._enabled = true;
  41060. };
  41061. /**
  41062. * Disables contributions to the sliding window sample set
  41063. * Samples will not be interpolated over the disabled period
  41064. */
  41065. PerformanceMonitor.prototype.disable = function () {
  41066. this._enabled = false;
  41067. //clear last sample to avoid interpolating over the disabled period when next enabled
  41068. this._lastFrameTimeMs = null;
  41069. };
  41070. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41071. /**
  41072. * Returns true if sampling is enabled
  41073. * @return true if enabled
  41074. */
  41075. get: function () {
  41076. return this._enabled;
  41077. },
  41078. enumerable: true,
  41079. configurable: true
  41080. });
  41081. /**
  41082. * Resets performance monitor
  41083. */
  41084. PerformanceMonitor.prototype.reset = function () {
  41085. //clear last sample to avoid interpolating over the disabled period when next enabled
  41086. this._lastFrameTimeMs = null;
  41087. //wipe record
  41088. this._rollingFrameTime.reset();
  41089. };
  41090. return PerformanceMonitor;
  41091. }());
  41092. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41093. /**
  41094. * RollingAverage
  41095. *
  41096. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41097. */
  41098. var RollingAverage = /** @class */ (function () {
  41099. /**
  41100. * constructor
  41101. * @param length The number of samples required to saturate the sliding window
  41102. */
  41103. function RollingAverage(length) {
  41104. this._samples = new Array(length);
  41105. this.reset();
  41106. }
  41107. /**
  41108. * Adds a sample to the sample set
  41109. * @param v The sample value
  41110. */
  41111. RollingAverage.prototype.add = function (v) {
  41112. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41113. var delta;
  41114. //we need to check if we've already wrapped round
  41115. if (this.isSaturated()) {
  41116. //remove bottom of stack from mean
  41117. var bottomValue = this._samples[this._pos];
  41118. delta = bottomValue - this.average;
  41119. this.average -= delta / (this._sampleCount - 1);
  41120. this._m2 -= delta * (bottomValue - this.average);
  41121. }
  41122. else {
  41123. this._sampleCount++;
  41124. }
  41125. //add new value to mean
  41126. delta = v - this.average;
  41127. this.average += delta / (this._sampleCount);
  41128. this._m2 += delta * (v - this.average);
  41129. //set the new variance
  41130. this.variance = this._m2 / (this._sampleCount - 1);
  41131. this._samples[this._pos] = v;
  41132. this._pos++;
  41133. this._pos %= this._samples.length; //positive wrap around
  41134. };
  41135. /**
  41136. * Returns previously added values or null if outside of history or outside the sliding window domain
  41137. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41138. * @return Value previously recorded with add() or null if outside of range
  41139. */
  41140. RollingAverage.prototype.history = function (i) {
  41141. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41142. return 0;
  41143. }
  41144. var i0 = this._wrapPosition(this._pos - 1.0);
  41145. return this._samples[this._wrapPosition(i0 - i)];
  41146. };
  41147. /**
  41148. * Returns true if enough samples have been taken to completely fill the sliding window
  41149. * @return true if sample-set saturated
  41150. */
  41151. RollingAverage.prototype.isSaturated = function () {
  41152. return this._sampleCount >= this._samples.length;
  41153. };
  41154. /**
  41155. * Resets the rolling average (equivalent to 0 samples taken so far)
  41156. */
  41157. RollingAverage.prototype.reset = function () {
  41158. this.average = 0;
  41159. this.variance = 0;
  41160. this._sampleCount = 0;
  41161. this._pos = 0;
  41162. this._m2 = 0;
  41163. };
  41164. /**
  41165. * Wraps a value around the sample range boundaries
  41166. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41167. * @return Wrapped position in sample range
  41168. */
  41169. RollingAverage.prototype._wrapPosition = function (i) {
  41170. var max = this._samples.length;
  41171. return ((i % max) + max) % max;
  41172. };
  41173. return RollingAverage;
  41174. }());
  41175. BABYLON.RollingAverage = RollingAverage;
  41176. })(BABYLON || (BABYLON = {}));
  41177. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41178. var BABYLON;
  41179. (function (BABYLON) {
  41180. /**
  41181. * "Static Class" containing the most commonly used helper while dealing with material for
  41182. * rendering purpose.
  41183. *
  41184. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41185. *
  41186. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41187. */
  41188. var MaterialHelper = /** @class */ (function () {
  41189. function MaterialHelper() {
  41190. }
  41191. /**
  41192. * Bind the current view position to an effect.
  41193. * @param effect The effect to be bound
  41194. * @param scene The scene the eyes position is used from
  41195. */
  41196. MaterialHelper.BindEyePosition = function (effect, scene) {
  41197. if (scene._forcedViewPosition) {
  41198. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41199. return;
  41200. }
  41201. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41202. };
  41203. /**
  41204. * Helps preparing the defines values about the UVs in used in the effect.
  41205. * UVs are shared as much as we can accross chanels in the shaders.
  41206. * @param texture The texture we are preparing the UVs for
  41207. * @param defines The defines to update
  41208. * @param key The chanel key "diffuse", "specular"... used in the shader
  41209. */
  41210. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41211. defines._needUVs = true;
  41212. defines[key] = true;
  41213. if (texture.getTextureMatrix().isIdentity(true)) {
  41214. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41215. if (texture.coordinatesIndex === 0) {
  41216. defines["MAINUV1"] = true;
  41217. }
  41218. else {
  41219. defines["MAINUV2"] = true;
  41220. }
  41221. }
  41222. else {
  41223. defines[key + "DIRECTUV"] = 0;
  41224. }
  41225. };
  41226. /**
  41227. * Binds a texture matrix value to its corrsponding uniform
  41228. * @param texture The texture to bind the matrix for
  41229. * @param uniformBuffer The uniform buffer receivin the data
  41230. * @param key The chanel key "diffuse", "specular"... used in the shader
  41231. */
  41232. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41233. var matrix = texture.getTextureMatrix();
  41234. if (!matrix.isIdentity(true)) {
  41235. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41236. }
  41237. };
  41238. /**
  41239. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41240. * @param mesh defines the current mesh
  41241. * @param scene defines the current scene
  41242. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41243. * @param pointsCloud defines if point cloud rendering has to be turned on
  41244. * @param fogEnabled defines if fog has to be turned on
  41245. * @param alphaTest defines if alpha testing has to be turned on
  41246. * @param defines defines the current list of defines
  41247. */
  41248. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41249. if (defines._areMiscDirty) {
  41250. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41251. defines["POINTSIZE"] = pointsCloud;
  41252. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41253. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41254. defines["ALPHATEST"] = alphaTest;
  41255. }
  41256. };
  41257. /**
  41258. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41259. * @param scene defines the current scene
  41260. * @param engine defines the current engine
  41261. * @param defines specifies the list of active defines
  41262. * @param useInstances defines if instances have to be turned on
  41263. * @param useClipPlane defines if clip plane have to be turned on
  41264. */
  41265. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41266. if (useClipPlane === void 0) { useClipPlane = null; }
  41267. var changed = false;
  41268. if (useClipPlane == null) {
  41269. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41270. }
  41271. if (defines["CLIPPLANE"] !== useClipPlane) {
  41272. defines["CLIPPLANE"] = useClipPlane;
  41273. changed = true;
  41274. }
  41275. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41276. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41277. changed = true;
  41278. }
  41279. if (defines["INSTANCES"] !== useInstances) {
  41280. defines["INSTANCES"] = useInstances;
  41281. changed = true;
  41282. }
  41283. if (changed) {
  41284. defines.markAsUnprocessed();
  41285. }
  41286. };
  41287. /**
  41288. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41289. * @param mesh The mesh containing the geometry data we will draw
  41290. * @param defines The defines to update
  41291. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41292. * @param useBones Precise whether bones should be used or not (override mesh info)
  41293. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41294. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41295. * @returns false if defines are considered not dirty and have not been checked
  41296. */
  41297. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41298. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41299. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41300. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41301. return false;
  41302. }
  41303. defines._normals = defines._needNormals;
  41304. defines._uvs = defines._needUVs;
  41305. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41306. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41307. defines["TANGENT"] = true;
  41308. }
  41309. if (defines._needUVs) {
  41310. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41311. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41312. }
  41313. else {
  41314. defines["UV1"] = false;
  41315. defines["UV2"] = false;
  41316. }
  41317. if (useVertexColor) {
  41318. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41319. defines["VERTEXCOLOR"] = hasVertexColors;
  41320. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41321. }
  41322. if (useBones) {
  41323. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41324. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41325. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41326. }
  41327. else {
  41328. defines["NUM_BONE_INFLUENCERS"] = 0;
  41329. defines["BonesPerMesh"] = 0;
  41330. }
  41331. }
  41332. if (useMorphTargets) {
  41333. var manager = mesh.morphTargetManager;
  41334. if (manager) {
  41335. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41336. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41337. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41338. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41339. }
  41340. else {
  41341. defines["MORPHTARGETS_TANGENT"] = false;
  41342. defines["MORPHTARGETS_NORMAL"] = false;
  41343. defines["MORPHTARGETS"] = false;
  41344. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41345. }
  41346. }
  41347. return true;
  41348. };
  41349. /**
  41350. * Prepares the defines related to the light information passed in parameter
  41351. * @param scene The scene we are intending to draw
  41352. * @param mesh The mesh the effect is compiling for
  41353. * @param defines The defines to update
  41354. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41355. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41356. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41357. * @returns true if normals will be required for the rest of the effect
  41358. */
  41359. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41360. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41361. if (disableLighting === void 0) { disableLighting = false; }
  41362. if (!defines._areLightsDirty) {
  41363. return defines._needNormals;
  41364. }
  41365. var lightIndex = 0;
  41366. var needNormals = false;
  41367. var needRebuild = false;
  41368. var lightmapMode = false;
  41369. var shadowEnabled = false;
  41370. var specularEnabled = false;
  41371. if (scene.lightsEnabled && !disableLighting) {
  41372. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41373. var light = _a[_i];
  41374. needNormals = true;
  41375. if (defines["LIGHT" + lightIndex] === undefined) {
  41376. needRebuild = true;
  41377. }
  41378. defines["LIGHT" + lightIndex] = true;
  41379. defines["SPOTLIGHT" + lightIndex] = false;
  41380. defines["HEMILIGHT" + lightIndex] = false;
  41381. defines["POINTLIGHT" + lightIndex] = false;
  41382. defines["DIRLIGHT" + lightIndex] = false;
  41383. var type;
  41384. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41385. type = "SPOTLIGHT" + lightIndex;
  41386. var spotLight = light;
  41387. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41388. }
  41389. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41390. type = "HEMILIGHT" + lightIndex;
  41391. }
  41392. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41393. type = "POINTLIGHT" + lightIndex;
  41394. }
  41395. else {
  41396. type = "DIRLIGHT" + lightIndex;
  41397. }
  41398. defines[type] = true;
  41399. // Specular
  41400. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41401. specularEnabled = true;
  41402. }
  41403. // Shadows
  41404. defines["SHADOW" + lightIndex] = false;
  41405. defines["SHADOWPCF" + lightIndex] = false;
  41406. defines["SHADOWPCSS" + lightIndex] = false;
  41407. defines["SHADOWPOISSON" + lightIndex] = false;
  41408. defines["SHADOWESM" + lightIndex] = false;
  41409. defines["SHADOWCUBE" + lightIndex] = false;
  41410. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41411. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41412. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41413. var shadowGenerator = light.getShadowGenerator();
  41414. if (shadowGenerator) {
  41415. shadowEnabled = true;
  41416. shadowGenerator.prepareDefines(defines, lightIndex);
  41417. }
  41418. }
  41419. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41420. lightmapMode = true;
  41421. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41422. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41423. }
  41424. else {
  41425. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41426. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41427. }
  41428. lightIndex++;
  41429. if (lightIndex === maxSimultaneousLights)
  41430. break;
  41431. }
  41432. }
  41433. defines["SPECULARTERM"] = specularEnabled;
  41434. defines["SHADOWS"] = shadowEnabled;
  41435. // Resetting all other lights if any
  41436. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41437. if (defines["LIGHT" + index] !== undefined) {
  41438. defines["LIGHT" + index] = false;
  41439. defines["HEMILIGHT" + lightIndex] = false;
  41440. defines["POINTLIGHT" + lightIndex] = false;
  41441. defines["DIRLIGHT" + lightIndex] = false;
  41442. defines["SPOTLIGHT" + lightIndex] = false;
  41443. defines["SHADOW" + lightIndex] = false;
  41444. }
  41445. }
  41446. var caps = scene.getEngine().getCaps();
  41447. if (defines["SHADOWFLOAT"] === undefined) {
  41448. needRebuild = true;
  41449. }
  41450. defines["SHADOWFLOAT"] = shadowEnabled &&
  41451. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41452. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41453. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41454. if (needRebuild) {
  41455. defines.rebuild();
  41456. }
  41457. return needNormals;
  41458. };
  41459. /**
  41460. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41461. * that won t be acctive due to defines being turned off.
  41462. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41463. * @param samplersList The samplers list
  41464. * @param defines The defines helping in the list generation
  41465. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41466. */
  41467. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41468. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41469. var uniformsList;
  41470. var uniformBuffersList = null;
  41471. if (uniformsListOrOptions.uniformsNames) {
  41472. var options = uniformsListOrOptions;
  41473. uniformsList = options.uniformsNames;
  41474. uniformBuffersList = options.uniformBuffersNames;
  41475. samplersList = options.samplers;
  41476. defines = options.defines;
  41477. maxSimultaneousLights = options.maxSimultaneousLights;
  41478. }
  41479. else {
  41480. uniformsList = uniformsListOrOptions;
  41481. if (!samplersList) {
  41482. samplersList = [];
  41483. }
  41484. }
  41485. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41486. if (!defines["LIGHT" + lightIndex]) {
  41487. break;
  41488. }
  41489. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41490. if (uniformBuffersList) {
  41491. uniformBuffersList.push("Light" + lightIndex);
  41492. }
  41493. samplersList.push("shadowSampler" + lightIndex);
  41494. samplersList.push("depthSampler" + lightIndex);
  41495. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41496. samplersList.push("projectionLightSampler" + lightIndex);
  41497. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41498. }
  41499. }
  41500. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41501. uniformsList.push("morphTargetInfluences");
  41502. }
  41503. };
  41504. /**
  41505. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41506. * @param defines The defines to update while falling back
  41507. * @param fallbacks The authorized effect fallbacks
  41508. * @param maxSimultaneousLights The maximum number of lights allowed
  41509. * @param rank the current rank of the Effect
  41510. * @returns The newly affected rank
  41511. */
  41512. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41513. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41514. if (rank === void 0) { rank = 0; }
  41515. var lightFallbackRank = 0;
  41516. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41517. if (!defines["LIGHT" + lightIndex]) {
  41518. break;
  41519. }
  41520. if (lightIndex > 0) {
  41521. lightFallbackRank = rank + lightIndex;
  41522. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41523. }
  41524. if (!defines["SHADOWS"]) {
  41525. if (defines["SHADOW" + lightIndex]) {
  41526. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41527. }
  41528. if (defines["SHADOWPCF" + lightIndex]) {
  41529. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41530. }
  41531. if (defines["SHADOWPCSS" + lightIndex]) {
  41532. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41533. }
  41534. if (defines["SHADOWPOISSON" + lightIndex]) {
  41535. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41536. }
  41537. if (defines["SHADOWESM" + lightIndex]) {
  41538. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41539. }
  41540. }
  41541. }
  41542. return lightFallbackRank++;
  41543. };
  41544. /**
  41545. * Prepares the list of attributes required for morph targets according to the effect defines.
  41546. * @param attribs The current list of supported attribs
  41547. * @param mesh The mesh to prepare the morph targets attributes for
  41548. * @param defines The current Defines of the effect
  41549. */
  41550. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41551. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41552. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41553. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41554. var manager = mesh.morphTargetManager;
  41555. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41556. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41557. for (var index = 0; index < influencers; index++) {
  41558. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41559. if (normal) {
  41560. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41561. }
  41562. if (tangent) {
  41563. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41564. }
  41565. if (attribs.length > maxAttributesCount) {
  41566. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41567. }
  41568. }
  41569. }
  41570. };
  41571. /**
  41572. * Prepares the list of attributes required for bones according to the effect defines.
  41573. * @param attribs The current list of supported attribs
  41574. * @param mesh The mesh to prepare the bones attributes for
  41575. * @param defines The current Defines of the effect
  41576. * @param fallbacks The current efffect fallback strategy
  41577. */
  41578. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41579. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41580. fallbacks.addCPUSkinningFallback(0, mesh);
  41581. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41582. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41583. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41584. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41585. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41586. }
  41587. }
  41588. };
  41589. /**
  41590. * Prepares the list of attributes required for instances according to the effect defines.
  41591. * @param attribs The current list of supported attribs
  41592. * @param defines The current Defines of the effect
  41593. */
  41594. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41595. if (defines["INSTANCES"]) {
  41596. attribs.push("world0");
  41597. attribs.push("world1");
  41598. attribs.push("world2");
  41599. attribs.push("world3");
  41600. }
  41601. };
  41602. /**
  41603. * Binds the light shadow information to the effect for the given mesh.
  41604. * @param light The light containing the generator
  41605. * @param scene The scene the lights belongs to
  41606. * @param mesh The mesh we are binding the information to render
  41607. * @param lightIndex The light index in the effect used to render the mesh
  41608. * @param effect The effect we are binding the data to
  41609. */
  41610. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41611. if (light.shadowEnabled && mesh.receiveShadows) {
  41612. var shadowGenerator = light.getShadowGenerator();
  41613. if (shadowGenerator) {
  41614. shadowGenerator.bindShadowLight(lightIndex, effect);
  41615. }
  41616. }
  41617. };
  41618. /**
  41619. * Binds the light information to the effect.
  41620. * @param light The light containing the generator
  41621. * @param effect The effect we are binding the data to
  41622. * @param lightIndex The light index in the effect used to render
  41623. */
  41624. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41625. light.transferToEffect(effect, lightIndex + "");
  41626. };
  41627. /**
  41628. * Binds the lights information from the scene to the effect for the given mesh.
  41629. * @param scene The scene the lights belongs to
  41630. * @param mesh The mesh we are binding the information to render
  41631. * @param effect The effect we are binding the data to
  41632. * @param defines The generated defines for the effect
  41633. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41634. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41635. */
  41636. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41637. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41638. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41639. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41640. for (var i = 0; i < len; i++) {
  41641. var light = mesh._lightSources[i];
  41642. var iAsString = i.toString();
  41643. var scaledIntensity = light.getScaledIntensity();
  41644. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41645. MaterialHelper.BindLightProperties(light, effect, i);
  41646. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41647. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41648. if (defines["SPECULARTERM"]) {
  41649. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41650. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41651. }
  41652. // Shadows
  41653. if (scene.shadowsEnabled) {
  41654. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41655. }
  41656. light._uniformBuffer.update();
  41657. }
  41658. };
  41659. /**
  41660. * Binds the fog information from the scene to the effect for the given mesh.
  41661. * @param scene The scene the lights belongs to
  41662. * @param mesh The mesh we are binding the information to render
  41663. * @param effect The effect we are binding the data to
  41664. */
  41665. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41666. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41667. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41668. effect.setColor3("vFogColor", scene.fogColor);
  41669. }
  41670. };
  41671. /**
  41672. * Binds the bones information from the mesh to the effect.
  41673. * @param mesh The mesh we are binding the information to render
  41674. * @param effect The effect we are binding the data to
  41675. */
  41676. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41677. if (!effect || !mesh) {
  41678. return;
  41679. }
  41680. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41681. mesh.computeBonesUsingShaders = false;
  41682. }
  41683. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41684. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41685. if (matrices) {
  41686. effect.setMatrices("mBones", matrices);
  41687. }
  41688. }
  41689. };
  41690. /**
  41691. * Binds the morph targets information from the mesh to the effect.
  41692. * @param abstractMesh The mesh we are binding the information to render
  41693. * @param effect The effect we are binding the data to
  41694. */
  41695. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41696. var manager = abstractMesh.morphTargetManager;
  41697. if (!abstractMesh || !manager) {
  41698. return;
  41699. }
  41700. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41701. };
  41702. /**
  41703. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41704. * @param defines The generated defines used in the effect
  41705. * @param effect The effect we are binding the data to
  41706. * @param scene The scene we are willing to render with logarithmic scale for
  41707. */
  41708. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41709. if (defines["LOGARITHMICDEPTH"]) {
  41710. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41711. }
  41712. };
  41713. /**
  41714. * Binds the clip plane information from the scene to the effect.
  41715. * @param scene The scene the clip plane information are extracted from
  41716. * @param effect The effect we are binding the data to
  41717. */
  41718. MaterialHelper.BindClipPlane = function (effect, scene) {
  41719. if (scene.clipPlane) {
  41720. var clipPlane = scene.clipPlane;
  41721. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41722. }
  41723. };
  41724. return MaterialHelper;
  41725. }());
  41726. BABYLON.MaterialHelper = MaterialHelper;
  41727. })(BABYLON || (BABYLON = {}));
  41728. //# sourceMappingURL=babylon.materialHelper.js.map
  41729. var BABYLON;
  41730. (function (BABYLON) {
  41731. var PushMaterial = /** @class */ (function (_super) {
  41732. __extends(PushMaterial, _super);
  41733. function PushMaterial(name, scene) {
  41734. var _this = _super.call(this, name, scene) || this;
  41735. _this._normalMatrix = new BABYLON.Matrix();
  41736. _this.storeEffectOnSubMeshes = true;
  41737. return _this;
  41738. }
  41739. PushMaterial.prototype.getEffect = function () {
  41740. return this._activeEffect;
  41741. };
  41742. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41743. if (!mesh) {
  41744. return false;
  41745. }
  41746. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41747. return true;
  41748. }
  41749. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41750. };
  41751. /**
  41752. * Binds the given world matrix to the active effect
  41753. *
  41754. * @param world the matrix to bind
  41755. */
  41756. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41757. this._activeEffect.setMatrix("world", world);
  41758. };
  41759. /**
  41760. * Binds the given normal matrix to the active effect
  41761. *
  41762. * @param normalMatrix the matrix to bind
  41763. */
  41764. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41765. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41766. };
  41767. PushMaterial.prototype.bind = function (world, mesh) {
  41768. if (!mesh) {
  41769. return;
  41770. }
  41771. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41772. };
  41773. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41774. if (effect === void 0) { effect = null; }
  41775. _super.prototype._afterBind.call(this, mesh);
  41776. this.getScene()._cachedEffect = effect;
  41777. };
  41778. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41779. if (visibility === void 0) { visibility = 1; }
  41780. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41781. };
  41782. return PushMaterial;
  41783. }(BABYLON.Material));
  41784. BABYLON.PushMaterial = PushMaterial;
  41785. })(BABYLON || (BABYLON = {}));
  41786. //# sourceMappingURL=babylon.pushMaterial.js.map
  41787. var BABYLON;
  41788. (function (BABYLON) {
  41789. /** @hidden */
  41790. var StandardMaterialDefines = /** @class */ (function (_super) {
  41791. __extends(StandardMaterialDefines, _super);
  41792. function StandardMaterialDefines() {
  41793. var _this = _super.call(this) || this;
  41794. _this.MAINUV1 = false;
  41795. _this.MAINUV2 = false;
  41796. _this.DIFFUSE = false;
  41797. _this.DIFFUSEDIRECTUV = 0;
  41798. _this.AMBIENT = false;
  41799. _this.AMBIENTDIRECTUV = 0;
  41800. _this.OPACITY = false;
  41801. _this.OPACITYDIRECTUV = 0;
  41802. _this.OPACITYRGB = false;
  41803. _this.REFLECTION = false;
  41804. _this.EMISSIVE = false;
  41805. _this.EMISSIVEDIRECTUV = 0;
  41806. _this.SPECULAR = false;
  41807. _this.SPECULARDIRECTUV = 0;
  41808. _this.BUMP = false;
  41809. _this.BUMPDIRECTUV = 0;
  41810. _this.PARALLAX = false;
  41811. _this.PARALLAXOCCLUSION = false;
  41812. _this.SPECULAROVERALPHA = false;
  41813. _this.CLIPPLANE = false;
  41814. _this.ALPHATEST = false;
  41815. _this.DEPTHPREPASS = false;
  41816. _this.ALPHAFROMDIFFUSE = false;
  41817. _this.POINTSIZE = false;
  41818. _this.FOG = false;
  41819. _this.SPECULARTERM = false;
  41820. _this.DIFFUSEFRESNEL = false;
  41821. _this.OPACITYFRESNEL = false;
  41822. _this.REFLECTIONFRESNEL = false;
  41823. _this.REFRACTIONFRESNEL = false;
  41824. _this.EMISSIVEFRESNEL = false;
  41825. _this.FRESNEL = false;
  41826. _this.NORMAL = false;
  41827. _this.UV1 = false;
  41828. _this.UV2 = false;
  41829. _this.VERTEXCOLOR = false;
  41830. _this.VERTEXALPHA = false;
  41831. _this.NUM_BONE_INFLUENCERS = 0;
  41832. _this.BonesPerMesh = 0;
  41833. _this.INSTANCES = false;
  41834. _this.GLOSSINESS = false;
  41835. _this.ROUGHNESS = false;
  41836. _this.EMISSIVEASILLUMINATION = false;
  41837. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41838. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41839. _this.LIGHTMAP = false;
  41840. _this.LIGHTMAPDIRECTUV = 0;
  41841. _this.OBJECTSPACE_NORMALMAP = false;
  41842. _this.USELIGHTMAPASSHADOWMAP = false;
  41843. _this.REFLECTIONMAP_3D = false;
  41844. _this.REFLECTIONMAP_SPHERICAL = false;
  41845. _this.REFLECTIONMAP_PLANAR = false;
  41846. _this.REFLECTIONMAP_CUBIC = false;
  41847. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41848. _this.REFLECTIONMAP_PROJECTION = false;
  41849. _this.REFLECTIONMAP_SKYBOX = false;
  41850. _this.REFLECTIONMAP_EXPLICIT = false;
  41851. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41852. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41853. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41854. _this.INVERTCUBICMAP = false;
  41855. _this.LOGARITHMICDEPTH = false;
  41856. _this.REFRACTION = false;
  41857. _this.REFRACTIONMAP_3D = false;
  41858. _this.REFLECTIONOVERALPHA = false;
  41859. _this.TWOSIDEDLIGHTING = false;
  41860. _this.SHADOWFLOAT = false;
  41861. _this.MORPHTARGETS = false;
  41862. _this.MORPHTARGETS_NORMAL = false;
  41863. _this.MORPHTARGETS_TANGENT = false;
  41864. _this.NUM_MORPH_INFLUENCERS = 0;
  41865. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41866. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41867. _this.IMAGEPROCESSING = false;
  41868. _this.VIGNETTE = false;
  41869. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41870. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41871. _this.TONEMAPPING = false;
  41872. _this.CONTRAST = false;
  41873. _this.COLORCURVES = false;
  41874. _this.COLORGRADING = false;
  41875. _this.COLORGRADING3D = false;
  41876. _this.SAMPLER3DGREENDEPTH = false;
  41877. _this.SAMPLER3DBGRMAP = false;
  41878. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41879. /**
  41880. * If the reflection texture on this material is in linear color space
  41881. * @hidden
  41882. */
  41883. _this.IS_REFLECTION_LINEAR = false;
  41884. /**
  41885. * If the refraction texture on this material is in linear color space
  41886. * @hidden
  41887. */
  41888. _this.IS_REFRACTION_LINEAR = false;
  41889. _this.EXPOSURE = false;
  41890. _this.rebuild();
  41891. return _this;
  41892. }
  41893. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41894. var modes = [
  41895. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41896. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41897. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41898. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41899. ];
  41900. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41901. var mode = modes_1[_i];
  41902. this[mode] = (mode === modeToEnable);
  41903. }
  41904. };
  41905. return StandardMaterialDefines;
  41906. }(BABYLON.MaterialDefines));
  41907. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41908. var StandardMaterial = /** @class */ (function (_super) {
  41909. __extends(StandardMaterial, _super);
  41910. function StandardMaterial(name, scene) {
  41911. var _this = _super.call(this, name, scene) || this;
  41912. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41913. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41914. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41915. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41916. _this.specularPower = 64;
  41917. _this._useAlphaFromDiffuseTexture = false;
  41918. _this._useEmissiveAsIllumination = false;
  41919. _this._linkEmissiveWithDiffuse = false;
  41920. _this._useSpecularOverAlpha = false;
  41921. _this._useReflectionOverAlpha = false;
  41922. _this._disableLighting = false;
  41923. _this._useObjectSpaceNormalMap = false;
  41924. _this._useParallax = false;
  41925. _this._useParallaxOcclusion = false;
  41926. _this.parallaxScaleBias = 0.05;
  41927. _this._roughness = 0;
  41928. _this.indexOfRefraction = 0.98;
  41929. _this.invertRefractionY = true;
  41930. /**
  41931. * Defines the alpha limits in alpha test mode
  41932. */
  41933. _this.alphaCutOff = 0.4;
  41934. _this._useLightmapAsShadowmap = false;
  41935. _this._useReflectionFresnelFromSpecular = false;
  41936. _this._useGlossinessFromSpecularMapAlpha = false;
  41937. _this._maxSimultaneousLights = 4;
  41938. /**
  41939. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41940. */
  41941. _this._invertNormalMapX = false;
  41942. /**
  41943. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41944. */
  41945. _this._invertNormalMapY = false;
  41946. /**
  41947. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41948. */
  41949. _this._twoSidedLighting = false;
  41950. _this._renderTargets = new BABYLON.SmartArray(16);
  41951. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  41952. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41953. // Setup the default processing configuration to the scene.
  41954. _this._attachImageProcessingConfiguration(null);
  41955. _this.getRenderTargetTextures = function () {
  41956. _this._renderTargets.reset();
  41957. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41958. _this._renderTargets.push(_this._reflectionTexture);
  41959. }
  41960. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41961. _this._renderTargets.push(_this._refractionTexture);
  41962. }
  41963. return _this._renderTargets;
  41964. };
  41965. return _this;
  41966. }
  41967. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  41968. /**
  41969. * Gets the image processing configuration used either in this material.
  41970. */
  41971. get: function () {
  41972. return this._imageProcessingConfiguration;
  41973. },
  41974. /**
  41975. * Sets the Default image processing configuration used either in the this material.
  41976. *
  41977. * If sets to null, the scene one is in use.
  41978. */
  41979. set: function (value) {
  41980. this._attachImageProcessingConfiguration(value);
  41981. // Ensure the effect will be rebuilt.
  41982. this._markAllSubMeshesAsTexturesDirty();
  41983. },
  41984. enumerable: true,
  41985. configurable: true
  41986. });
  41987. /**
  41988. * Attaches a new image processing configuration to the Standard Material.
  41989. * @param configuration
  41990. */
  41991. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41992. var _this = this;
  41993. if (configuration === this._imageProcessingConfiguration) {
  41994. return;
  41995. }
  41996. // Detaches observer.
  41997. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41998. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41999. }
  42000. // Pick the scene configuration if needed.
  42001. if (!configuration) {
  42002. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42003. }
  42004. else {
  42005. this._imageProcessingConfiguration = configuration;
  42006. }
  42007. // Attaches observer.
  42008. if (this._imageProcessingConfiguration) {
  42009. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42010. _this._markAllSubMeshesAsImageProcessingDirty();
  42011. });
  42012. }
  42013. };
  42014. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42015. /**
  42016. * Gets wether the color curves effect is enabled.
  42017. */
  42018. get: function () {
  42019. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42020. },
  42021. /**
  42022. * Sets wether the color curves effect is enabled.
  42023. */
  42024. set: function (value) {
  42025. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42026. },
  42027. enumerable: true,
  42028. configurable: true
  42029. });
  42030. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42031. /**
  42032. * Gets wether the color grading effect is enabled.
  42033. */
  42034. get: function () {
  42035. return this.imageProcessingConfiguration.colorGradingEnabled;
  42036. },
  42037. /**
  42038. * Gets wether the color grading effect is enabled.
  42039. */
  42040. set: function (value) {
  42041. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42042. },
  42043. enumerable: true,
  42044. configurable: true
  42045. });
  42046. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42047. /**
  42048. * Gets wether tonemapping is enabled or not.
  42049. */
  42050. get: function () {
  42051. return this._imageProcessingConfiguration.toneMappingEnabled;
  42052. },
  42053. /**
  42054. * Sets wether tonemapping is enabled or not
  42055. */
  42056. set: function (value) {
  42057. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42058. },
  42059. enumerable: true,
  42060. configurable: true
  42061. });
  42062. ;
  42063. ;
  42064. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42065. /**
  42066. * The camera exposure used on this material.
  42067. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42068. * This corresponds to a photographic exposure.
  42069. */
  42070. get: function () {
  42071. return this._imageProcessingConfiguration.exposure;
  42072. },
  42073. /**
  42074. * The camera exposure used on this material.
  42075. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42076. * This corresponds to a photographic exposure.
  42077. */
  42078. set: function (value) {
  42079. this._imageProcessingConfiguration.exposure = value;
  42080. },
  42081. enumerable: true,
  42082. configurable: true
  42083. });
  42084. ;
  42085. ;
  42086. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42087. /**
  42088. * Gets The camera contrast used on this material.
  42089. */
  42090. get: function () {
  42091. return this._imageProcessingConfiguration.contrast;
  42092. },
  42093. /**
  42094. * Sets The camera contrast used on this material.
  42095. */
  42096. set: function (value) {
  42097. this._imageProcessingConfiguration.contrast = value;
  42098. },
  42099. enumerable: true,
  42100. configurable: true
  42101. });
  42102. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42103. /**
  42104. * Gets the Color Grading 2D Lookup Texture.
  42105. */
  42106. get: function () {
  42107. return this._imageProcessingConfiguration.colorGradingTexture;
  42108. },
  42109. /**
  42110. * Sets the Color Grading 2D Lookup Texture.
  42111. */
  42112. set: function (value) {
  42113. this._imageProcessingConfiguration.colorGradingTexture = value;
  42114. },
  42115. enumerable: true,
  42116. configurable: true
  42117. });
  42118. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42119. /**
  42120. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42121. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42122. * 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;
  42123. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42124. */
  42125. get: function () {
  42126. return this._imageProcessingConfiguration.colorCurves;
  42127. },
  42128. /**
  42129. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42130. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42131. * 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;
  42132. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42133. */
  42134. set: function (value) {
  42135. this._imageProcessingConfiguration.colorCurves = value;
  42136. },
  42137. enumerable: true,
  42138. configurable: true
  42139. });
  42140. StandardMaterial.prototype.getClassName = function () {
  42141. return "StandardMaterial";
  42142. };
  42143. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42144. get: function () {
  42145. return this._useLogarithmicDepth;
  42146. },
  42147. set: function (value) {
  42148. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42149. this._markAllSubMeshesAsMiscDirty();
  42150. },
  42151. enumerable: true,
  42152. configurable: true
  42153. });
  42154. StandardMaterial.prototype.needAlphaBlending = function () {
  42155. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42156. };
  42157. StandardMaterial.prototype.needAlphaTesting = function () {
  42158. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42159. };
  42160. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42161. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42162. };
  42163. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42164. return this._diffuseTexture;
  42165. };
  42166. /**
  42167. * Child classes can use it to update shaders
  42168. */
  42169. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42170. if (useInstances === void 0) { useInstances = false; }
  42171. if (subMesh.effect && this.isFrozen) {
  42172. if (this._wasPreviouslyReady && subMesh.effect) {
  42173. return true;
  42174. }
  42175. }
  42176. if (!subMesh._materialDefines) {
  42177. subMesh._materialDefines = new StandardMaterialDefines();
  42178. }
  42179. var scene = this.getScene();
  42180. var defines = subMesh._materialDefines;
  42181. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42182. if (defines._renderId === scene.getRenderId()) {
  42183. return true;
  42184. }
  42185. }
  42186. var engine = scene.getEngine();
  42187. // Lights
  42188. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42189. // Textures
  42190. if (defines._areTexturesDirty) {
  42191. defines._needUVs = false;
  42192. defines.MAINUV1 = false;
  42193. defines.MAINUV2 = false;
  42194. if (scene.texturesEnabled) {
  42195. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42196. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42197. return false;
  42198. }
  42199. else {
  42200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42201. }
  42202. }
  42203. else {
  42204. defines.DIFFUSE = false;
  42205. }
  42206. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42207. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42208. return false;
  42209. }
  42210. else {
  42211. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42212. }
  42213. }
  42214. else {
  42215. defines.AMBIENT = false;
  42216. }
  42217. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42218. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42219. return false;
  42220. }
  42221. else {
  42222. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42223. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42224. }
  42225. }
  42226. else {
  42227. defines.OPACITY = false;
  42228. }
  42229. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42230. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42231. return false;
  42232. }
  42233. else {
  42234. defines._needNormals = true;
  42235. defines.REFLECTION = true;
  42236. defines.ROUGHNESS = (this._roughness > 0);
  42237. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42238. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42239. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42240. switch (this._reflectionTexture.coordinatesMode) {
  42241. case BABYLON.Texture.EXPLICIT_MODE:
  42242. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42243. break;
  42244. case BABYLON.Texture.PLANAR_MODE:
  42245. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42246. break;
  42247. case BABYLON.Texture.PROJECTION_MODE:
  42248. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42249. break;
  42250. case BABYLON.Texture.SKYBOX_MODE:
  42251. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42252. break;
  42253. case BABYLON.Texture.SPHERICAL_MODE:
  42254. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42255. break;
  42256. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42257. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42258. break;
  42259. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42260. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42261. break;
  42262. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42263. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42264. break;
  42265. case BABYLON.Texture.CUBIC_MODE:
  42266. case BABYLON.Texture.INVCUBIC_MODE:
  42267. default:
  42268. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42269. break;
  42270. }
  42271. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42272. }
  42273. }
  42274. else {
  42275. defines.REFLECTION = false;
  42276. }
  42277. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42278. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42279. return false;
  42280. }
  42281. else {
  42282. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42283. }
  42284. }
  42285. else {
  42286. defines.EMISSIVE = false;
  42287. }
  42288. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42289. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42290. return false;
  42291. }
  42292. else {
  42293. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42294. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42295. }
  42296. }
  42297. else {
  42298. defines.LIGHTMAP = false;
  42299. }
  42300. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42301. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42302. return false;
  42303. }
  42304. else {
  42305. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42306. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42307. }
  42308. }
  42309. else {
  42310. defines.SPECULAR = false;
  42311. }
  42312. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42313. // Bump texure can not be not blocking.
  42314. if (!this._bumpTexture.isReady()) {
  42315. return false;
  42316. }
  42317. else {
  42318. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42319. defines.PARALLAX = this._useParallax;
  42320. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42321. }
  42322. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42323. }
  42324. else {
  42325. defines.BUMP = false;
  42326. }
  42327. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42328. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42329. return false;
  42330. }
  42331. else {
  42332. defines._needUVs = true;
  42333. defines.REFRACTION = true;
  42334. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42335. }
  42336. }
  42337. else {
  42338. defines.REFRACTION = false;
  42339. }
  42340. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42341. }
  42342. else {
  42343. defines.DIFFUSE = false;
  42344. defines.AMBIENT = false;
  42345. defines.OPACITY = false;
  42346. defines.REFLECTION = false;
  42347. defines.EMISSIVE = false;
  42348. defines.LIGHTMAP = false;
  42349. defines.BUMP = false;
  42350. defines.REFRACTION = false;
  42351. }
  42352. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42353. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42354. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42355. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42356. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42357. }
  42358. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42359. if (!this._imageProcessingConfiguration.isReady()) {
  42360. return false;
  42361. }
  42362. this._imageProcessingConfiguration.prepareDefines(defines);
  42363. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42364. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42365. }
  42366. if (defines._areFresnelDirty) {
  42367. if (StandardMaterial.FresnelEnabled) {
  42368. // Fresnel
  42369. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42370. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42371. this._reflectionFresnelParameters) {
  42372. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42373. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42374. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42375. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42376. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42377. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42378. defines._needNormals = true;
  42379. defines.FRESNEL = true;
  42380. }
  42381. }
  42382. else {
  42383. defines.FRESNEL = false;
  42384. }
  42385. }
  42386. // Misc.
  42387. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42388. // Attribs
  42389. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42390. // Values that need to be evaluated on every frame
  42391. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42392. // Get correct effect
  42393. if (defines.isDirty) {
  42394. defines.markAsProcessed();
  42395. scene.resetCachedMaterial();
  42396. // Fallbacks
  42397. var fallbacks = new BABYLON.EffectFallbacks();
  42398. if (defines.REFLECTION) {
  42399. fallbacks.addFallback(0, "REFLECTION");
  42400. }
  42401. if (defines.SPECULAR) {
  42402. fallbacks.addFallback(0, "SPECULAR");
  42403. }
  42404. if (defines.BUMP) {
  42405. fallbacks.addFallback(0, "BUMP");
  42406. }
  42407. if (defines.PARALLAX) {
  42408. fallbacks.addFallback(1, "PARALLAX");
  42409. }
  42410. if (defines.PARALLAXOCCLUSION) {
  42411. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42412. }
  42413. if (defines.SPECULAROVERALPHA) {
  42414. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42415. }
  42416. if (defines.FOG) {
  42417. fallbacks.addFallback(1, "FOG");
  42418. }
  42419. if (defines.POINTSIZE) {
  42420. fallbacks.addFallback(0, "POINTSIZE");
  42421. }
  42422. if (defines.LOGARITHMICDEPTH) {
  42423. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42424. }
  42425. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42426. if (defines.SPECULARTERM) {
  42427. fallbacks.addFallback(0, "SPECULARTERM");
  42428. }
  42429. if (defines.DIFFUSEFRESNEL) {
  42430. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42431. }
  42432. if (defines.OPACITYFRESNEL) {
  42433. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42434. }
  42435. if (defines.REFLECTIONFRESNEL) {
  42436. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42437. }
  42438. if (defines.EMISSIVEFRESNEL) {
  42439. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42440. }
  42441. if (defines.FRESNEL) {
  42442. fallbacks.addFallback(4, "FRESNEL");
  42443. }
  42444. //Attributes
  42445. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42446. if (defines.NORMAL) {
  42447. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42448. }
  42449. if (defines.UV1) {
  42450. attribs.push(BABYLON.VertexBuffer.UVKind);
  42451. }
  42452. if (defines.UV2) {
  42453. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42454. }
  42455. if (defines.VERTEXCOLOR) {
  42456. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42457. }
  42458. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42459. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42460. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42461. var shaderName = "default";
  42462. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42463. "vFogInfos", "vFogColor", "pointSize",
  42464. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42465. "mBones",
  42466. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42467. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42468. "vReflectionPosition", "vReflectionSize",
  42469. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42470. ];
  42471. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42472. var uniformBuffers = ["Material", "Scene"];
  42473. if (BABYLON.ImageProcessingConfiguration) {
  42474. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42475. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42476. }
  42477. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42478. uniformsNames: uniforms,
  42479. uniformBuffersNames: uniformBuffers,
  42480. samplers: samplers,
  42481. defines: defines,
  42482. maxSimultaneousLights: this._maxSimultaneousLights
  42483. });
  42484. if (this.customShaderNameResolve) {
  42485. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42486. }
  42487. var join = defines.toString();
  42488. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42489. attributes: attribs,
  42490. uniformsNames: uniforms,
  42491. uniformBuffersNames: uniformBuffers,
  42492. samplers: samplers,
  42493. defines: join,
  42494. fallbacks: fallbacks,
  42495. onCompiled: this.onCompiled,
  42496. onError: this.onError,
  42497. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42498. }, engine), defines);
  42499. this.buildUniformLayout();
  42500. }
  42501. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42502. return false;
  42503. }
  42504. defines._renderId = scene.getRenderId();
  42505. this._wasPreviouslyReady = true;
  42506. return true;
  42507. };
  42508. StandardMaterial.prototype.buildUniformLayout = function () {
  42509. // Order is important !
  42510. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42511. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42512. this._uniformBuffer.addUniform("opacityParts", 4);
  42513. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42514. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42515. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42516. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42517. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42518. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42519. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42520. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42521. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42522. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42523. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42524. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42525. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42526. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42527. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42528. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42529. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42530. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42531. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42532. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42533. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42534. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42535. this._uniformBuffer.addUniform("specularMatrix", 16);
  42536. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42537. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42538. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42539. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42540. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42541. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42542. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42543. this._uniformBuffer.addUniform("pointSize", 1);
  42544. this._uniformBuffer.create();
  42545. };
  42546. StandardMaterial.prototype.unbind = function () {
  42547. if (this._activeEffect) {
  42548. var needFlag = false;
  42549. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42550. this._activeEffect.setTexture("reflection2DSampler", null);
  42551. needFlag = true;
  42552. }
  42553. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42554. this._activeEffect.setTexture("refraction2DSampler", null);
  42555. needFlag = true;
  42556. }
  42557. if (needFlag) {
  42558. this._markAllSubMeshesAsTexturesDirty();
  42559. }
  42560. }
  42561. _super.prototype.unbind.call(this);
  42562. };
  42563. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42564. var scene = this.getScene();
  42565. var defines = subMesh._materialDefines;
  42566. if (!defines) {
  42567. return;
  42568. }
  42569. var effect = subMesh.effect;
  42570. if (!effect) {
  42571. return;
  42572. }
  42573. this._activeEffect = effect;
  42574. // Matrices
  42575. this.bindOnlyWorldMatrix(world);
  42576. // Normal Matrix
  42577. if (defines.OBJECTSPACE_NORMALMAP) {
  42578. world.toNormalMatrix(this._normalMatrix);
  42579. this.bindOnlyNormalMatrix(this._normalMatrix);
  42580. }
  42581. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42582. // Bones
  42583. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42584. if (mustRebind) {
  42585. this._uniformBuffer.bindToEffect(effect, "Material");
  42586. this.bindViewProjection(effect);
  42587. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42588. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42589. // Fresnel
  42590. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42591. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42592. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42593. }
  42594. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42595. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42596. }
  42597. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42598. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42599. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42600. }
  42601. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42602. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42603. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42604. }
  42605. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42606. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42607. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42608. }
  42609. }
  42610. // Textures
  42611. if (scene.texturesEnabled) {
  42612. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42613. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42614. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42615. if (this._diffuseTexture.hasAlpha) {
  42616. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42617. }
  42618. }
  42619. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42620. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42621. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42622. }
  42623. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42624. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42625. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42626. }
  42627. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42628. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42629. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42630. if (this._reflectionTexture.boundingBoxSize) {
  42631. var cubeTexture = this._reflectionTexture;
  42632. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42633. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42634. }
  42635. }
  42636. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42637. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42638. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42639. }
  42640. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42641. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42642. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42643. }
  42644. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42645. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42646. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42647. }
  42648. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42649. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42650. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42651. if (scene._mirroredCameraPosition) {
  42652. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42653. }
  42654. else {
  42655. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42656. }
  42657. }
  42658. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42659. var depth = 1.0;
  42660. if (!this._refractionTexture.isCube) {
  42661. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42662. if (this._refractionTexture.depth) {
  42663. depth = this._refractionTexture.depth;
  42664. }
  42665. }
  42666. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42667. }
  42668. }
  42669. // Point size
  42670. if (this.pointsCloud) {
  42671. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42672. }
  42673. if (defines.SPECULARTERM) {
  42674. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42675. }
  42676. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42677. // Diffuse
  42678. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42679. }
  42680. // Textures
  42681. if (scene.texturesEnabled) {
  42682. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42683. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42684. }
  42685. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42686. effect.setTexture("ambientSampler", this._ambientTexture);
  42687. }
  42688. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42689. effect.setTexture("opacitySampler", this._opacityTexture);
  42690. }
  42691. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42692. if (this._reflectionTexture.isCube) {
  42693. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42694. }
  42695. else {
  42696. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42697. }
  42698. }
  42699. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42700. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42701. }
  42702. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42703. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42704. }
  42705. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42706. effect.setTexture("specularSampler", this._specularTexture);
  42707. }
  42708. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42709. effect.setTexture("bumpSampler", this._bumpTexture);
  42710. }
  42711. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42712. var depth = 1.0;
  42713. if (this._refractionTexture.isCube) {
  42714. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42715. }
  42716. else {
  42717. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42718. }
  42719. }
  42720. }
  42721. // Clip plane
  42722. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42723. // Colors
  42724. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42725. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42726. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42727. }
  42728. if (mustRebind || !this.isFrozen) {
  42729. // Lights
  42730. if (scene.lightsEnabled && !this._disableLighting) {
  42731. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42732. }
  42733. // View
  42734. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42735. this.bindView(effect);
  42736. }
  42737. // Fog
  42738. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42739. // Morph targets
  42740. if (defines.NUM_MORPH_INFLUENCERS) {
  42741. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42742. }
  42743. // Log. depth
  42744. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42745. // image processing
  42746. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42747. this._imageProcessingConfiguration.bind(this._activeEffect);
  42748. }
  42749. }
  42750. this._uniformBuffer.update();
  42751. this._afterBind(mesh, this._activeEffect);
  42752. };
  42753. StandardMaterial.prototype.getAnimatables = function () {
  42754. var results = [];
  42755. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42756. results.push(this._diffuseTexture);
  42757. }
  42758. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42759. results.push(this._ambientTexture);
  42760. }
  42761. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42762. results.push(this._opacityTexture);
  42763. }
  42764. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42765. results.push(this._reflectionTexture);
  42766. }
  42767. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42768. results.push(this._emissiveTexture);
  42769. }
  42770. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42771. results.push(this._specularTexture);
  42772. }
  42773. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42774. results.push(this._bumpTexture);
  42775. }
  42776. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42777. results.push(this._lightmapTexture);
  42778. }
  42779. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42780. results.push(this._refractionTexture);
  42781. }
  42782. return results;
  42783. };
  42784. StandardMaterial.prototype.getActiveTextures = function () {
  42785. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42786. if (this._diffuseTexture) {
  42787. activeTextures.push(this._diffuseTexture);
  42788. }
  42789. if (this._ambientTexture) {
  42790. activeTextures.push(this._ambientTexture);
  42791. }
  42792. if (this._opacityTexture) {
  42793. activeTextures.push(this._opacityTexture);
  42794. }
  42795. if (this._reflectionTexture) {
  42796. activeTextures.push(this._reflectionTexture);
  42797. }
  42798. if (this._emissiveTexture) {
  42799. activeTextures.push(this._emissiveTexture);
  42800. }
  42801. if (this._specularTexture) {
  42802. activeTextures.push(this._specularTexture);
  42803. }
  42804. if (this._bumpTexture) {
  42805. activeTextures.push(this._bumpTexture);
  42806. }
  42807. if (this._lightmapTexture) {
  42808. activeTextures.push(this._lightmapTexture);
  42809. }
  42810. if (this._refractionTexture) {
  42811. activeTextures.push(this._refractionTexture);
  42812. }
  42813. return activeTextures;
  42814. };
  42815. StandardMaterial.prototype.hasTexture = function (texture) {
  42816. if (_super.prototype.hasTexture.call(this, texture)) {
  42817. return true;
  42818. }
  42819. if (this._diffuseTexture === texture) {
  42820. return true;
  42821. }
  42822. if (this._ambientTexture === texture) {
  42823. return true;
  42824. }
  42825. if (this._opacityTexture === texture) {
  42826. return true;
  42827. }
  42828. if (this._reflectionTexture === texture) {
  42829. return true;
  42830. }
  42831. if (this._emissiveTexture === texture) {
  42832. return true;
  42833. }
  42834. if (this._specularTexture === texture) {
  42835. return true;
  42836. }
  42837. if (this._bumpTexture === texture) {
  42838. return true;
  42839. }
  42840. if (this._lightmapTexture === texture) {
  42841. return true;
  42842. }
  42843. if (this._refractionTexture === texture) {
  42844. return true;
  42845. }
  42846. return false;
  42847. };
  42848. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42849. if (forceDisposeTextures) {
  42850. if (this._diffuseTexture) {
  42851. this._diffuseTexture.dispose();
  42852. }
  42853. if (this._ambientTexture) {
  42854. this._ambientTexture.dispose();
  42855. }
  42856. if (this._opacityTexture) {
  42857. this._opacityTexture.dispose();
  42858. }
  42859. if (this._reflectionTexture) {
  42860. this._reflectionTexture.dispose();
  42861. }
  42862. if (this._emissiveTexture) {
  42863. this._emissiveTexture.dispose();
  42864. }
  42865. if (this._specularTexture) {
  42866. this._specularTexture.dispose();
  42867. }
  42868. if (this._bumpTexture) {
  42869. this._bumpTexture.dispose();
  42870. }
  42871. if (this._lightmapTexture) {
  42872. this._lightmapTexture.dispose();
  42873. }
  42874. if (this._refractionTexture) {
  42875. this._refractionTexture.dispose();
  42876. }
  42877. }
  42878. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42879. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42880. }
  42881. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42882. };
  42883. StandardMaterial.prototype.clone = function (name) {
  42884. var _this = this;
  42885. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42886. result.name = name;
  42887. result.id = name;
  42888. return result;
  42889. };
  42890. StandardMaterial.prototype.serialize = function () {
  42891. return BABYLON.SerializationHelper.Serialize(this);
  42892. };
  42893. // Statics
  42894. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42895. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42896. };
  42897. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42898. get: function () {
  42899. return StandardMaterial._DiffuseTextureEnabled;
  42900. },
  42901. set: function (value) {
  42902. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42903. return;
  42904. }
  42905. StandardMaterial._DiffuseTextureEnabled = value;
  42906. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42907. },
  42908. enumerable: true,
  42909. configurable: true
  42910. });
  42911. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42912. get: function () {
  42913. return StandardMaterial._AmbientTextureEnabled;
  42914. },
  42915. set: function (value) {
  42916. if (StandardMaterial._AmbientTextureEnabled === value) {
  42917. return;
  42918. }
  42919. StandardMaterial._AmbientTextureEnabled = value;
  42920. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42921. },
  42922. enumerable: true,
  42923. configurable: true
  42924. });
  42925. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  42926. get: function () {
  42927. return StandardMaterial._OpacityTextureEnabled;
  42928. },
  42929. set: function (value) {
  42930. if (StandardMaterial._OpacityTextureEnabled === value) {
  42931. return;
  42932. }
  42933. StandardMaterial._OpacityTextureEnabled = value;
  42934. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42935. },
  42936. enumerable: true,
  42937. configurable: true
  42938. });
  42939. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  42940. get: function () {
  42941. return StandardMaterial._ReflectionTextureEnabled;
  42942. },
  42943. set: function (value) {
  42944. if (StandardMaterial._ReflectionTextureEnabled === value) {
  42945. return;
  42946. }
  42947. StandardMaterial._ReflectionTextureEnabled = value;
  42948. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42949. },
  42950. enumerable: true,
  42951. configurable: true
  42952. });
  42953. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  42954. get: function () {
  42955. return StandardMaterial._EmissiveTextureEnabled;
  42956. },
  42957. set: function (value) {
  42958. if (StandardMaterial._EmissiveTextureEnabled === value) {
  42959. return;
  42960. }
  42961. StandardMaterial._EmissiveTextureEnabled = value;
  42962. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42963. },
  42964. enumerable: true,
  42965. configurable: true
  42966. });
  42967. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  42968. get: function () {
  42969. return StandardMaterial._SpecularTextureEnabled;
  42970. },
  42971. set: function (value) {
  42972. if (StandardMaterial._SpecularTextureEnabled === value) {
  42973. return;
  42974. }
  42975. StandardMaterial._SpecularTextureEnabled = value;
  42976. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42977. },
  42978. enumerable: true,
  42979. configurable: true
  42980. });
  42981. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  42982. get: function () {
  42983. return StandardMaterial._BumpTextureEnabled;
  42984. },
  42985. set: function (value) {
  42986. if (StandardMaterial._BumpTextureEnabled === value) {
  42987. return;
  42988. }
  42989. StandardMaterial._BumpTextureEnabled = value;
  42990. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42991. },
  42992. enumerable: true,
  42993. configurable: true
  42994. });
  42995. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  42996. get: function () {
  42997. return StandardMaterial._LightmapTextureEnabled;
  42998. },
  42999. set: function (value) {
  43000. if (StandardMaterial._LightmapTextureEnabled === value) {
  43001. return;
  43002. }
  43003. StandardMaterial._LightmapTextureEnabled = value;
  43004. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43005. },
  43006. enumerable: true,
  43007. configurable: true
  43008. });
  43009. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43010. get: function () {
  43011. return StandardMaterial._RefractionTextureEnabled;
  43012. },
  43013. set: function (value) {
  43014. if (StandardMaterial._RefractionTextureEnabled === value) {
  43015. return;
  43016. }
  43017. StandardMaterial._RefractionTextureEnabled = value;
  43018. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43019. },
  43020. enumerable: true,
  43021. configurable: true
  43022. });
  43023. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43024. get: function () {
  43025. return StandardMaterial._ColorGradingTextureEnabled;
  43026. },
  43027. set: function (value) {
  43028. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43029. return;
  43030. }
  43031. StandardMaterial._ColorGradingTextureEnabled = value;
  43032. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43033. },
  43034. enumerable: true,
  43035. configurable: true
  43036. });
  43037. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43038. get: function () {
  43039. return StandardMaterial._FresnelEnabled;
  43040. },
  43041. set: function (value) {
  43042. if (StandardMaterial._FresnelEnabled === value) {
  43043. return;
  43044. }
  43045. StandardMaterial._FresnelEnabled = value;
  43046. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43047. },
  43048. enumerable: true,
  43049. configurable: true
  43050. });
  43051. // Flags used to enable or disable a type of texture for all Standard Materials
  43052. StandardMaterial._DiffuseTextureEnabled = true;
  43053. StandardMaterial._AmbientTextureEnabled = true;
  43054. StandardMaterial._OpacityTextureEnabled = true;
  43055. StandardMaterial._ReflectionTextureEnabled = true;
  43056. StandardMaterial._EmissiveTextureEnabled = true;
  43057. StandardMaterial._SpecularTextureEnabled = true;
  43058. StandardMaterial._BumpTextureEnabled = true;
  43059. StandardMaterial._LightmapTextureEnabled = true;
  43060. StandardMaterial._RefractionTextureEnabled = true;
  43061. StandardMaterial._ColorGradingTextureEnabled = true;
  43062. StandardMaterial._FresnelEnabled = true;
  43063. __decorate([
  43064. BABYLON.serializeAsTexture("diffuseTexture")
  43065. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43066. __decorate([
  43067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43068. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43069. __decorate([
  43070. BABYLON.serializeAsTexture("ambientTexture")
  43071. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43072. __decorate([
  43073. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43074. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43075. __decorate([
  43076. BABYLON.serializeAsTexture("opacityTexture")
  43077. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43078. __decorate([
  43079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43080. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43081. __decorate([
  43082. BABYLON.serializeAsTexture("reflectionTexture")
  43083. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43084. __decorate([
  43085. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43086. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43087. __decorate([
  43088. BABYLON.serializeAsTexture("emissiveTexture")
  43089. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43090. __decorate([
  43091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43092. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43093. __decorate([
  43094. BABYLON.serializeAsTexture("specularTexture")
  43095. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43096. __decorate([
  43097. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43098. ], StandardMaterial.prototype, "specularTexture", void 0);
  43099. __decorate([
  43100. BABYLON.serializeAsTexture("bumpTexture")
  43101. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43102. __decorate([
  43103. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43104. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43105. __decorate([
  43106. BABYLON.serializeAsTexture("lightmapTexture")
  43107. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43108. __decorate([
  43109. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43110. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43111. __decorate([
  43112. BABYLON.serializeAsTexture("refractionTexture")
  43113. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43114. __decorate([
  43115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43116. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43117. __decorate([
  43118. BABYLON.serializeAsColor3("ambient")
  43119. ], StandardMaterial.prototype, "ambientColor", void 0);
  43120. __decorate([
  43121. BABYLON.serializeAsColor3("diffuse")
  43122. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43123. __decorate([
  43124. BABYLON.serializeAsColor3("specular")
  43125. ], StandardMaterial.prototype, "specularColor", void 0);
  43126. __decorate([
  43127. BABYLON.serializeAsColor3("emissive")
  43128. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43129. __decorate([
  43130. BABYLON.serialize()
  43131. ], StandardMaterial.prototype, "specularPower", void 0);
  43132. __decorate([
  43133. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43134. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43135. __decorate([
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43138. __decorate([
  43139. BABYLON.serialize("useEmissiveAsIllumination")
  43140. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43141. __decorate([
  43142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43143. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43144. __decorate([
  43145. BABYLON.serialize("linkEmissiveWithDiffuse")
  43146. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43147. __decorate([
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43150. __decorate([
  43151. BABYLON.serialize("useSpecularOverAlpha")
  43152. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43153. __decorate([
  43154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43155. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43156. __decorate([
  43157. BABYLON.serialize("useReflectionOverAlpha")
  43158. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43159. __decorate([
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43161. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43162. __decorate([
  43163. BABYLON.serialize("disableLighting")
  43164. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43165. __decorate([
  43166. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43167. ], StandardMaterial.prototype, "disableLighting", void 0);
  43168. __decorate([
  43169. BABYLON.serialize("useObjectSpaceNormalMap")
  43170. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43171. __decorate([
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43174. __decorate([
  43175. BABYLON.serialize("useParallax")
  43176. ], StandardMaterial.prototype, "_useParallax", void 0);
  43177. __decorate([
  43178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43179. ], StandardMaterial.prototype, "useParallax", void 0);
  43180. __decorate([
  43181. BABYLON.serialize("useParallaxOcclusion")
  43182. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43183. __decorate([
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43186. __decorate([
  43187. BABYLON.serialize()
  43188. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43189. __decorate([
  43190. BABYLON.serialize("roughness")
  43191. ], StandardMaterial.prototype, "_roughness", void 0);
  43192. __decorate([
  43193. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43194. ], StandardMaterial.prototype, "roughness", void 0);
  43195. __decorate([
  43196. BABYLON.serialize()
  43197. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43198. __decorate([
  43199. BABYLON.serialize()
  43200. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43201. __decorate([
  43202. BABYLON.serialize()
  43203. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43204. __decorate([
  43205. BABYLON.serialize("useLightmapAsShadowmap")
  43206. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43207. __decorate([
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43209. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43210. __decorate([
  43211. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43212. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43213. __decorate([
  43214. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43215. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43216. __decorate([
  43217. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43218. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43219. __decorate([
  43220. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43221. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43222. __decorate([
  43223. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43224. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43225. __decorate([
  43226. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43227. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43228. __decorate([
  43229. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43230. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43231. __decorate([
  43232. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43233. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43234. __decorate([
  43235. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43236. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43237. __decorate([
  43238. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43239. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43240. __decorate([
  43241. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43242. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43243. __decorate([
  43244. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43245. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43246. __decorate([
  43247. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43248. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43249. __decorate([
  43250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43251. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43252. __decorate([
  43253. BABYLON.serialize("maxSimultaneousLights")
  43254. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43255. __decorate([
  43256. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43257. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43258. __decorate([
  43259. BABYLON.serialize("invertNormalMapX")
  43260. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43261. __decorate([
  43262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43263. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43264. __decorate([
  43265. BABYLON.serialize("invertNormalMapY")
  43266. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43267. __decorate([
  43268. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43269. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43270. __decorate([
  43271. BABYLON.serialize("twoSidedLighting")
  43272. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43273. __decorate([
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43275. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43276. __decorate([
  43277. BABYLON.serialize()
  43278. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43279. return StandardMaterial;
  43280. }(BABYLON.PushMaterial));
  43281. BABYLON.StandardMaterial = StandardMaterial;
  43282. })(BABYLON || (BABYLON = {}));
  43283. //# sourceMappingURL=babylon.standardMaterial.js.map
  43284. var BABYLON;
  43285. (function (BABYLON) {
  43286. /**
  43287. * Manages the defines for the PBR Material.
  43288. * @hiddenChildren
  43289. */
  43290. var PBRMaterialDefines = /** @class */ (function (_super) {
  43291. __extends(PBRMaterialDefines, _super);
  43292. /**
  43293. * Initializes the PBR Material defines.
  43294. */
  43295. function PBRMaterialDefines() {
  43296. var _this = _super.call(this) || this;
  43297. _this.PBR = true;
  43298. _this.MAINUV1 = false;
  43299. _this.MAINUV2 = false;
  43300. _this.UV1 = false;
  43301. _this.UV2 = false;
  43302. _this.ALBEDO = false;
  43303. _this.ALBEDODIRECTUV = 0;
  43304. _this.VERTEXCOLOR = false;
  43305. _this.AMBIENT = false;
  43306. _this.AMBIENTDIRECTUV = 0;
  43307. _this.AMBIENTINGRAYSCALE = false;
  43308. _this.OPACITY = false;
  43309. _this.VERTEXALPHA = false;
  43310. _this.OPACITYDIRECTUV = 0;
  43311. _this.OPACITYRGB = false;
  43312. _this.ALPHATEST = false;
  43313. _this.DEPTHPREPASS = false;
  43314. _this.ALPHABLEND = false;
  43315. _this.ALPHAFROMALBEDO = false;
  43316. _this.ALPHATESTVALUE = "0.5";
  43317. _this.SPECULAROVERALPHA = false;
  43318. _this.RADIANCEOVERALPHA = false;
  43319. _this.ALPHAFRESNEL = false;
  43320. _this.LINEARALPHAFRESNEL = false;
  43321. _this.PREMULTIPLYALPHA = false;
  43322. _this.EMISSIVE = false;
  43323. _this.EMISSIVEDIRECTUV = 0;
  43324. _this.REFLECTIVITY = false;
  43325. _this.REFLECTIVITYDIRECTUV = 0;
  43326. _this.SPECULARTERM = false;
  43327. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43328. _this.MICROSURFACEAUTOMATIC = false;
  43329. _this.LODBASEDMICROSFURACE = false;
  43330. _this.MICROSURFACEMAP = false;
  43331. _this.MICROSURFACEMAPDIRECTUV = 0;
  43332. _this.METALLICWORKFLOW = false;
  43333. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43334. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43335. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43336. _this.AOSTOREINMETALMAPRED = false;
  43337. _this.ENVIRONMENTBRDF = false;
  43338. _this.NORMAL = false;
  43339. _this.TANGENT = false;
  43340. _this.BUMP = false;
  43341. _this.BUMPDIRECTUV = 0;
  43342. _this.OBJECTSPACE_NORMALMAP = false;
  43343. _this.PARALLAX = false;
  43344. _this.PARALLAXOCCLUSION = false;
  43345. _this.NORMALXYSCALE = true;
  43346. _this.LIGHTMAP = false;
  43347. _this.LIGHTMAPDIRECTUV = 0;
  43348. _this.USELIGHTMAPASSHADOWMAP = false;
  43349. _this.GAMMALIGHTMAP = false;
  43350. _this.REFLECTION = false;
  43351. _this.REFLECTIONMAP_3D = false;
  43352. _this.REFLECTIONMAP_SPHERICAL = false;
  43353. _this.REFLECTIONMAP_PLANAR = false;
  43354. _this.REFLECTIONMAP_CUBIC = false;
  43355. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43356. _this.REFLECTIONMAP_PROJECTION = false;
  43357. _this.REFLECTIONMAP_SKYBOX = false;
  43358. _this.REFLECTIONMAP_EXPLICIT = false;
  43359. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43360. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43361. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43362. _this.INVERTCUBICMAP = false;
  43363. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43364. _this.USESPHERICALINVERTEX = false;
  43365. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43366. _this.LODINREFLECTIONALPHA = false;
  43367. _this.GAMMAREFLECTION = false;
  43368. _this.RGBDREFLECTION = false;
  43369. _this.RADIANCEOCCLUSION = false;
  43370. _this.HORIZONOCCLUSION = false;
  43371. _this.REFRACTION = false;
  43372. _this.REFRACTIONMAP_3D = false;
  43373. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43374. _this.LODINREFRACTIONALPHA = false;
  43375. _this.GAMMAREFRACTION = false;
  43376. _this.RGBDREFRACTION = false;
  43377. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43378. _this.INSTANCES = false;
  43379. _this.NUM_BONE_INFLUENCERS = 0;
  43380. _this.BonesPerMesh = 0;
  43381. _this.NONUNIFORMSCALING = false;
  43382. _this.MORPHTARGETS = false;
  43383. _this.MORPHTARGETS_NORMAL = false;
  43384. _this.MORPHTARGETS_TANGENT = false;
  43385. _this.NUM_MORPH_INFLUENCERS = 0;
  43386. _this.IMAGEPROCESSING = false;
  43387. _this.VIGNETTE = false;
  43388. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43389. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43390. _this.TONEMAPPING = false;
  43391. _this.CONTRAST = false;
  43392. _this.COLORCURVES = false;
  43393. _this.COLORGRADING = false;
  43394. _this.COLORGRADING3D = false;
  43395. _this.SAMPLER3DGREENDEPTH = false;
  43396. _this.SAMPLER3DBGRMAP = false;
  43397. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43398. _this.EXPOSURE = false;
  43399. _this.USEPHYSICALLIGHTFALLOFF = false;
  43400. _this.TWOSIDEDLIGHTING = false;
  43401. _this.SHADOWFLOAT = false;
  43402. _this.CLIPPLANE = false;
  43403. _this.POINTSIZE = false;
  43404. _this.FOG = false;
  43405. _this.LOGARITHMICDEPTH = false;
  43406. _this.FORCENORMALFORWARD = false;
  43407. _this.SPECULARAA = false;
  43408. _this.UNLIT = false;
  43409. _this.rebuild();
  43410. return _this;
  43411. }
  43412. /**
  43413. * Resets the PBR Material defines.
  43414. */
  43415. PBRMaterialDefines.prototype.reset = function () {
  43416. _super.prototype.reset.call(this);
  43417. this.ALPHATESTVALUE = "0.5";
  43418. this.PBR = true;
  43419. };
  43420. return PBRMaterialDefines;
  43421. }(BABYLON.MaterialDefines));
  43422. /**
  43423. * The Physically based material base class of BJS.
  43424. *
  43425. * This offers the main features of a standard PBR material.
  43426. * For more information, please refer to the documentation :
  43427. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43428. */
  43429. var PBRBaseMaterial = /** @class */ (function (_super) {
  43430. __extends(PBRBaseMaterial, _super);
  43431. /**
  43432. * Instantiates a new PBRMaterial instance.
  43433. *
  43434. * @param name The material name
  43435. * @param scene The scene the material will be use in.
  43436. */
  43437. function PBRBaseMaterial(name, scene) {
  43438. var _this = _super.call(this, name, scene) || this;
  43439. /**
  43440. * Intensity of the direct lights e.g. the four lights available in your scene.
  43441. * This impacts both the direct diffuse and specular highlights.
  43442. */
  43443. _this._directIntensity = 1.0;
  43444. /**
  43445. * Intensity of the emissive part of the material.
  43446. * This helps controlling the emissive effect without modifying the emissive color.
  43447. */
  43448. _this._emissiveIntensity = 1.0;
  43449. /**
  43450. * Intensity of the environment e.g. how much the environment will light the object
  43451. * either through harmonics for rough material or through the refelction for shiny ones.
  43452. */
  43453. _this._environmentIntensity = 1.0;
  43454. /**
  43455. * This is a special control allowing the reduction of the specular highlights coming from the
  43456. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43457. */
  43458. _this._specularIntensity = 1.0;
  43459. /**
  43460. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43461. */
  43462. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43463. /**
  43464. * Debug Control allowing disabling the bump map on this material.
  43465. */
  43466. _this._disableBumpMap = false;
  43467. /**
  43468. * AKA Occlusion Texture Intensity in other nomenclature.
  43469. */
  43470. _this._ambientTextureStrength = 1.0;
  43471. /**
  43472. * The color of a material in ambient lighting.
  43473. */
  43474. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43475. /**
  43476. * AKA Diffuse Color in other nomenclature.
  43477. */
  43478. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43479. /**
  43480. * AKA Specular Color in other nomenclature.
  43481. */
  43482. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43483. /**
  43484. * The color applied when light is reflected from a material.
  43485. */
  43486. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43487. /**
  43488. * The color applied when light is emitted from a material.
  43489. */
  43490. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43491. /**
  43492. * AKA Glossiness in other nomenclature.
  43493. */
  43494. _this._microSurface = 0.9;
  43495. /**
  43496. * source material index of refraction (IOR)' / 'destination material IOR.
  43497. */
  43498. _this._indexOfRefraction = 0.66;
  43499. /**
  43500. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43501. */
  43502. _this._invertRefractionY = false;
  43503. /**
  43504. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43505. * Materials half opaque for instance using refraction could benefit from this control.
  43506. */
  43507. _this._linkRefractionWithTransparency = false;
  43508. /**
  43509. * Specifies that the material will use the light map as a show map.
  43510. */
  43511. _this._useLightmapAsShadowmap = false;
  43512. /**
  43513. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43514. * makes the reflect vector face the model (under horizon).
  43515. */
  43516. _this._useHorizonOcclusion = true;
  43517. /**
  43518. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43519. * too much the area relying on ambient texture to define their ambient occlusion.
  43520. */
  43521. _this._useRadianceOcclusion = true;
  43522. /**
  43523. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43524. */
  43525. _this._useAlphaFromAlbedoTexture = false;
  43526. /**
  43527. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43528. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43529. */
  43530. _this._useSpecularOverAlpha = true;
  43531. /**
  43532. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43533. */
  43534. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43535. /**
  43536. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43537. */
  43538. _this._useRoughnessFromMetallicTextureAlpha = true;
  43539. /**
  43540. * Specifies if the metallic texture contains the roughness information in its green channel.
  43541. */
  43542. _this._useRoughnessFromMetallicTextureGreen = false;
  43543. /**
  43544. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43545. */
  43546. _this._useMetallnessFromMetallicTextureBlue = false;
  43547. /**
  43548. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43549. */
  43550. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43551. /**
  43552. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43553. */
  43554. _this._useAmbientInGrayScale = false;
  43555. /**
  43556. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43557. * The material will try to infer what glossiness each pixel should be.
  43558. */
  43559. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43560. /**
  43561. * BJS is using an harcoded light falloff based on a manually sets up range.
  43562. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43563. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43564. */
  43565. _this._usePhysicalLightFalloff = true;
  43566. /**
  43567. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43568. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43569. */
  43570. _this._useRadianceOverAlpha = true;
  43571. /**
  43572. * Allows using an object space normal map (instead of tangent space).
  43573. */
  43574. _this._useObjectSpaceNormalMap = false;
  43575. /**
  43576. * Allows using the bump map in parallax mode.
  43577. */
  43578. _this._useParallax = false;
  43579. /**
  43580. * Allows using the bump map in parallax occlusion mode.
  43581. */
  43582. _this._useParallaxOcclusion = false;
  43583. /**
  43584. * Controls the scale bias of the parallax mode.
  43585. */
  43586. _this._parallaxScaleBias = 0.05;
  43587. /**
  43588. * If sets to true, disables all the lights affecting the material.
  43589. */
  43590. _this._disableLighting = false;
  43591. /**
  43592. * Number of Simultaneous lights allowed on the material.
  43593. */
  43594. _this._maxSimultaneousLights = 4;
  43595. /**
  43596. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43597. */
  43598. _this._invertNormalMapX = false;
  43599. /**
  43600. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43601. */
  43602. _this._invertNormalMapY = false;
  43603. /**
  43604. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43605. */
  43606. _this._twoSidedLighting = false;
  43607. /**
  43608. * Defines the alpha limits in alpha test mode.
  43609. */
  43610. _this._alphaCutOff = 0.4;
  43611. /**
  43612. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43613. */
  43614. _this._forceAlphaTest = false;
  43615. /**
  43616. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43617. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43618. */
  43619. _this._useAlphaFresnel = false;
  43620. /**
  43621. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43622. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43623. */
  43624. _this._useLinearAlphaFresnel = false;
  43625. /**
  43626. * The transparency mode of the material.
  43627. */
  43628. _this._transparencyMode = null;
  43629. /**
  43630. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43631. * from cos thetav and roughness:
  43632. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43633. */
  43634. _this._environmentBRDFTexture = null;
  43635. /**
  43636. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43637. */
  43638. _this._forceIrradianceInFragment = false;
  43639. /**
  43640. * Force normal to face away from face.
  43641. */
  43642. _this._forceNormalForward = false;
  43643. /**
  43644. * Enables specular anti aliasing in the PBR shader.
  43645. * It will both interacts on the Geometry for analytical and IBL lighting.
  43646. * It also prefilter the roughness map based on the bump values.
  43647. */
  43648. _this._enableSpecularAntiAliasing = false;
  43649. /**
  43650. * Stores the available render targets.
  43651. */
  43652. _this._renderTargets = new BABYLON.SmartArray(16);
  43653. /**
  43654. * Sets the global ambient color for the material used in lighting calculations.
  43655. */
  43656. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43657. /**
  43658. * If set to true, no lighting calculations will be applied.
  43659. */
  43660. _this._unlit = false;
  43661. // Setup the default processing configuration to the scene.
  43662. _this._attachImageProcessingConfiguration(null);
  43663. _this.getRenderTargetTextures = function () {
  43664. _this._renderTargets.reset();
  43665. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43666. _this._renderTargets.push(_this._reflectionTexture);
  43667. }
  43668. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43669. _this._renderTargets.push(_this._refractionTexture);
  43670. }
  43671. return _this._renderTargets;
  43672. };
  43673. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43674. return _this;
  43675. }
  43676. /**
  43677. * Attaches a new image processing configuration to the PBR Material.
  43678. * @param configuration
  43679. */
  43680. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43681. var _this = this;
  43682. if (configuration === this._imageProcessingConfiguration) {
  43683. return;
  43684. }
  43685. // Detaches observer.
  43686. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43687. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43688. }
  43689. // Pick the scene configuration if needed.
  43690. if (!configuration) {
  43691. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43692. }
  43693. else {
  43694. this._imageProcessingConfiguration = configuration;
  43695. }
  43696. // Attaches observer.
  43697. if (this._imageProcessingConfiguration) {
  43698. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43699. _this._markAllSubMeshesAsImageProcessingDirty();
  43700. });
  43701. }
  43702. };
  43703. /**
  43704. * Gets the name of the material class.
  43705. */
  43706. PBRBaseMaterial.prototype.getClassName = function () {
  43707. return "PBRBaseMaterial";
  43708. };
  43709. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43710. /**
  43711. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43712. */
  43713. get: function () {
  43714. return this._useLogarithmicDepth;
  43715. },
  43716. /**
  43717. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43718. */
  43719. set: function (value) {
  43720. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43721. },
  43722. enumerable: true,
  43723. configurable: true
  43724. });
  43725. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43726. /**
  43727. * Gets the current transparency mode.
  43728. */
  43729. get: function () {
  43730. return this._transparencyMode;
  43731. },
  43732. /**
  43733. * Sets the transparency mode of the material.
  43734. *
  43735. * | Value | Type | Description |
  43736. * | ----- | ----------------------------------- | ----------- |
  43737. * | 0 | OPAQUE | |
  43738. * | 1 | ALPHATEST | |
  43739. * | 2 | ALPHABLEND | |
  43740. * | 3 | ALPHATESTANDBLEND | |
  43741. *
  43742. */
  43743. set: function (value) {
  43744. if (this._transparencyMode === value) {
  43745. return;
  43746. }
  43747. this._transparencyMode = value;
  43748. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43749. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43750. },
  43751. enumerable: true,
  43752. configurable: true
  43753. });
  43754. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43755. /**
  43756. * Returns true if alpha blending should be disabled.
  43757. */
  43758. get: function () {
  43759. return (this._linkRefractionWithTransparency ||
  43760. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43761. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43762. },
  43763. enumerable: true,
  43764. configurable: true
  43765. });
  43766. /**
  43767. * Specifies whether or not this material should be rendered in alpha blend mode.
  43768. */
  43769. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43770. if (this._disableAlphaBlending) {
  43771. return false;
  43772. }
  43773. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43774. };
  43775. /**
  43776. * Specifies if the mesh will require alpha blending.
  43777. * @param mesh - BJS mesh.
  43778. */
  43779. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43780. if (this._disableAlphaBlending) {
  43781. return false;
  43782. }
  43783. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43784. };
  43785. /**
  43786. * Specifies whether or not this material should be rendered in alpha test mode.
  43787. */
  43788. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43789. if (this._forceAlphaTest) {
  43790. return true;
  43791. }
  43792. if (this._linkRefractionWithTransparency) {
  43793. return false;
  43794. }
  43795. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43796. };
  43797. /**
  43798. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43799. */
  43800. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43801. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43802. };
  43803. /**
  43804. * Gets the texture used for the alpha test.
  43805. */
  43806. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43807. return this._albedoTexture;
  43808. };
  43809. /**
  43810. * Specifies that the submesh is ready to be used.
  43811. * @param mesh - BJS mesh.
  43812. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43813. * @param useInstances - Specifies that instances should be used.
  43814. * @returns - boolean indicating that the submesh is ready or not.
  43815. */
  43816. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43817. if (subMesh.effect && this.isFrozen) {
  43818. if (this._wasPreviouslyReady) {
  43819. return true;
  43820. }
  43821. }
  43822. if (!subMesh._materialDefines) {
  43823. subMesh._materialDefines = new PBRMaterialDefines();
  43824. }
  43825. var defines = subMesh._materialDefines;
  43826. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43827. if (defines._renderId === this.getScene().getRenderId()) {
  43828. return true;
  43829. }
  43830. }
  43831. var scene = this.getScene();
  43832. var engine = scene.getEngine();
  43833. if (defines._areTexturesDirty) {
  43834. if (scene.texturesEnabled) {
  43835. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43836. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43837. return false;
  43838. }
  43839. }
  43840. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43841. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43842. return false;
  43843. }
  43844. }
  43845. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43846. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43847. return false;
  43848. }
  43849. }
  43850. var reflectionTexture = this._getReflectionTexture();
  43851. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43852. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43853. return false;
  43854. }
  43855. }
  43856. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43857. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43858. return false;
  43859. }
  43860. }
  43861. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43862. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43863. return false;
  43864. }
  43865. }
  43866. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43867. if (this._metallicTexture) {
  43868. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43869. return false;
  43870. }
  43871. }
  43872. else if (this._reflectivityTexture) {
  43873. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43874. return false;
  43875. }
  43876. }
  43877. if (this._microSurfaceTexture) {
  43878. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43879. return false;
  43880. }
  43881. }
  43882. }
  43883. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43884. // Bump texture cannot be not blocking.
  43885. if (!this._bumpTexture.isReady()) {
  43886. return false;
  43887. }
  43888. }
  43889. var refractionTexture = this._getRefractionTexture();
  43890. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43891. if (!refractionTexture.isReadyOrNotBlocking()) {
  43892. return false;
  43893. }
  43894. }
  43895. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43896. // This is blocking.
  43897. if (!this._environmentBRDFTexture.isReady()) {
  43898. return false;
  43899. }
  43900. }
  43901. }
  43902. }
  43903. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43904. if (!this._imageProcessingConfiguration.isReady()) {
  43905. return false;
  43906. }
  43907. }
  43908. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43909. mesh.createNormals(true);
  43910. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43911. }
  43912. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43913. if (effect) {
  43914. scene.resetCachedMaterial();
  43915. subMesh.setEffect(effect, defines);
  43916. this.buildUniformLayout();
  43917. }
  43918. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43919. return false;
  43920. }
  43921. defines._renderId = scene.getRenderId();
  43922. this._wasPreviouslyReady = true;
  43923. return true;
  43924. };
  43925. /**
  43926. * Specifies if the material uses metallic roughness workflow.
  43927. * @returns boolean specifiying if the material uses metallic roughness workflow.
  43928. */
  43929. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  43930. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  43931. return true;
  43932. }
  43933. return false;
  43934. };
  43935. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  43936. if (onCompiled === void 0) { onCompiled = null; }
  43937. if (onError === void 0) { onError = null; }
  43938. if (useInstances === void 0) { useInstances = null; }
  43939. if (useClipPlane === void 0) { useClipPlane = null; }
  43940. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  43941. if (!defines.isDirty) {
  43942. return null;
  43943. }
  43944. defines.markAsProcessed();
  43945. var scene = this.getScene();
  43946. var engine = scene.getEngine();
  43947. // Fallbacks
  43948. var fallbacks = new BABYLON.EffectFallbacks();
  43949. var fallbackRank = 0;
  43950. if (defines.USESPHERICALINVERTEX) {
  43951. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  43952. }
  43953. if (defines.FOG) {
  43954. fallbacks.addFallback(fallbackRank, "FOG");
  43955. }
  43956. if (defines.SPECULARAA) {
  43957. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  43958. }
  43959. if (defines.POINTSIZE) {
  43960. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  43961. }
  43962. if (defines.LOGARITHMICDEPTH) {
  43963. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  43964. }
  43965. if (defines.PARALLAX) {
  43966. fallbacks.addFallback(fallbackRank, "PARALLAX");
  43967. }
  43968. if (defines.PARALLAXOCCLUSION) {
  43969. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  43970. }
  43971. if (defines.ENVIRONMENTBRDF) {
  43972. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  43973. }
  43974. if (defines.TANGENT) {
  43975. fallbacks.addFallback(fallbackRank++, "TANGENT");
  43976. }
  43977. if (defines.BUMP) {
  43978. fallbacks.addFallback(fallbackRank++, "BUMP");
  43979. }
  43980. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  43981. if (defines.SPECULARTERM) {
  43982. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  43983. }
  43984. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  43985. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  43986. }
  43987. if (defines.LIGHTMAP) {
  43988. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  43989. }
  43990. if (defines.NORMAL) {
  43991. fallbacks.addFallback(fallbackRank++, "NORMAL");
  43992. }
  43993. if (defines.AMBIENT) {
  43994. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  43995. }
  43996. if (defines.EMISSIVE) {
  43997. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  43998. }
  43999. if (defines.VERTEXCOLOR) {
  44000. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44001. }
  44002. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44003. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44004. }
  44005. if (defines.MORPHTARGETS) {
  44006. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44007. }
  44008. //Attributes
  44009. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44010. if (defines.NORMAL) {
  44011. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44012. }
  44013. if (defines.TANGENT) {
  44014. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44015. }
  44016. if (defines.UV1) {
  44017. attribs.push(BABYLON.VertexBuffer.UVKind);
  44018. }
  44019. if (defines.UV2) {
  44020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44021. }
  44022. if (defines.VERTEXCOLOR) {
  44023. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44024. }
  44025. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44026. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44027. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44028. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44029. "vFogInfos", "vFogColor", "pointSize",
  44030. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44031. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44032. "mBones",
  44033. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44034. "vLightingIntensity",
  44035. "logarithmicDepthConstant",
  44036. "vSphericalX", "vSphericalY", "vSphericalZ",
  44037. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44038. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44039. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44040. "vTangentSpaceParams"
  44041. ];
  44042. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44043. "bumpSampler", "lightmapSampler", "opacitySampler",
  44044. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44045. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44046. "microSurfaceSampler", "environmentBrdfSampler"];
  44047. var uniformBuffers = ["Material", "Scene"];
  44048. if (BABYLON.ImageProcessingConfiguration) {
  44049. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44050. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44051. }
  44052. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44053. uniformsNames: uniforms,
  44054. uniformBuffersNames: uniformBuffers,
  44055. samplers: samplers,
  44056. defines: defines,
  44057. maxSimultaneousLights: this._maxSimultaneousLights
  44058. });
  44059. var join = defines.toString();
  44060. return engine.createEffect("pbr", {
  44061. attributes: attribs,
  44062. uniformsNames: uniforms,
  44063. uniformBuffersNames: uniformBuffers,
  44064. samplers: samplers,
  44065. defines: join,
  44066. fallbacks: fallbacks,
  44067. onCompiled: onCompiled,
  44068. onError: onError,
  44069. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44070. }, engine);
  44071. };
  44072. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44073. if (useInstances === void 0) { useInstances = null; }
  44074. if (useClipPlane === void 0) { useClipPlane = null; }
  44075. var scene = this.getScene();
  44076. var engine = scene.getEngine();
  44077. // Lights
  44078. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44079. defines._needNormals = true;
  44080. // Textures
  44081. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44082. if (defines._areTexturesDirty) {
  44083. defines._needUVs = false;
  44084. if (scene.texturesEnabled) {
  44085. if (scene.getEngine().getCaps().textureLOD) {
  44086. defines.LODBASEDMICROSFURACE = true;
  44087. }
  44088. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44089. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44090. }
  44091. else {
  44092. defines.ALBEDO = false;
  44093. }
  44094. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44096. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44097. }
  44098. else {
  44099. defines.AMBIENT = false;
  44100. }
  44101. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44102. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44103. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44104. }
  44105. else {
  44106. defines.OPACITY = false;
  44107. }
  44108. var reflectionTexture = this._getReflectionTexture();
  44109. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44110. defines.REFLECTION = true;
  44111. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44112. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44113. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44114. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44115. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44116. defines.INVERTCUBICMAP = true;
  44117. }
  44118. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44119. switch (reflectionTexture.coordinatesMode) {
  44120. case BABYLON.Texture.EXPLICIT_MODE:
  44121. defines.REFLECTIONMAP_EXPLICIT = true;
  44122. break;
  44123. case BABYLON.Texture.PLANAR_MODE:
  44124. defines.REFLECTIONMAP_PLANAR = true;
  44125. break;
  44126. case BABYLON.Texture.PROJECTION_MODE:
  44127. defines.REFLECTIONMAP_PROJECTION = true;
  44128. break;
  44129. case BABYLON.Texture.SKYBOX_MODE:
  44130. defines.REFLECTIONMAP_SKYBOX = true;
  44131. break;
  44132. case BABYLON.Texture.SPHERICAL_MODE:
  44133. defines.REFLECTIONMAP_SPHERICAL = true;
  44134. break;
  44135. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44136. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44137. break;
  44138. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44139. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44140. break;
  44141. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44142. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44143. break;
  44144. case BABYLON.Texture.CUBIC_MODE:
  44145. case BABYLON.Texture.INVCUBIC_MODE:
  44146. default:
  44147. defines.REFLECTIONMAP_CUBIC = true;
  44148. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44149. break;
  44150. }
  44151. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44152. if (reflectionTexture.sphericalPolynomial) {
  44153. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44154. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44155. defines.USESPHERICALINVERTEX = false;
  44156. }
  44157. else {
  44158. defines.USESPHERICALINVERTEX = true;
  44159. }
  44160. }
  44161. }
  44162. }
  44163. else {
  44164. defines.REFLECTION = false;
  44165. defines.REFLECTIONMAP_3D = false;
  44166. defines.REFLECTIONMAP_SPHERICAL = false;
  44167. defines.REFLECTIONMAP_PLANAR = false;
  44168. defines.REFLECTIONMAP_CUBIC = false;
  44169. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44170. defines.REFLECTIONMAP_PROJECTION = false;
  44171. defines.REFLECTIONMAP_SKYBOX = false;
  44172. defines.REFLECTIONMAP_EXPLICIT = false;
  44173. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44174. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44175. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44176. defines.INVERTCUBICMAP = false;
  44177. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44178. defines.USESPHERICALINVERTEX = false;
  44179. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44180. defines.LODINREFLECTIONALPHA = false;
  44181. defines.GAMMAREFLECTION = false;
  44182. defines.RGBDREFLECTION = false;
  44183. }
  44184. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44186. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44187. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44188. }
  44189. else {
  44190. defines.LIGHTMAP = false;
  44191. }
  44192. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44193. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44194. }
  44195. else {
  44196. defines.EMISSIVE = false;
  44197. }
  44198. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44199. if (this._metallicTexture) {
  44200. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44201. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44202. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44203. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44204. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44205. }
  44206. else if (this._reflectivityTexture) {
  44207. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44208. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44209. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44210. }
  44211. else {
  44212. defines.REFLECTIVITY = false;
  44213. }
  44214. if (this._microSurfaceTexture) {
  44215. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44216. }
  44217. else {
  44218. defines.MICROSURFACEMAP = false;
  44219. }
  44220. }
  44221. else {
  44222. defines.REFLECTIVITY = false;
  44223. defines.MICROSURFACEMAP = false;
  44224. }
  44225. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44226. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44227. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44228. defines.PARALLAX = true;
  44229. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44230. }
  44231. else {
  44232. defines.PARALLAX = false;
  44233. }
  44234. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44235. }
  44236. else {
  44237. defines.BUMP = false;
  44238. }
  44239. var refractionTexture = this._getRefractionTexture();
  44240. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44241. defines.REFRACTION = true;
  44242. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44243. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44244. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44245. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44246. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44247. if (this._linkRefractionWithTransparency) {
  44248. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44249. }
  44250. }
  44251. else {
  44252. defines.REFRACTION = false;
  44253. }
  44254. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44255. defines.ENVIRONMENTBRDF = true;
  44256. }
  44257. else {
  44258. defines.ENVIRONMENTBRDF = false;
  44259. }
  44260. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44261. defines.ALPHAFROMALBEDO = true;
  44262. }
  44263. else {
  44264. defines.ALPHAFROMALBEDO = false;
  44265. }
  44266. }
  44267. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44268. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44269. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44270. if (!this.backFaceCulling && this._twoSidedLighting) {
  44271. defines.TWOSIDEDLIGHTING = true;
  44272. }
  44273. else {
  44274. defines.TWOSIDEDLIGHTING = false;
  44275. }
  44276. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44277. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44278. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44279. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44280. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44281. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44282. }
  44283. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44284. this._imageProcessingConfiguration.prepareDefines(defines);
  44285. }
  44286. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44287. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44288. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44289. // Misc.
  44290. if (defines._areMiscDirty) {
  44291. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44292. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44293. }
  44294. // Values that need to be evaluated on every frame
  44295. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44296. // Attribs
  44297. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44298. };
  44299. /**
  44300. * Force shader compilation
  44301. */
  44302. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44303. var _this = this;
  44304. var localOptions = __assign({ clipPlane: false }, options);
  44305. var defines = new PBRMaterialDefines();
  44306. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44307. if (effect.isReady()) {
  44308. if (onCompiled) {
  44309. onCompiled(this);
  44310. }
  44311. }
  44312. else {
  44313. effect.onCompileObservable.add(function () {
  44314. if (onCompiled) {
  44315. onCompiled(_this);
  44316. }
  44317. });
  44318. }
  44319. };
  44320. /**
  44321. * Initializes the uniform buffer layout for the shader.
  44322. */
  44323. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44324. // Order is important !
  44325. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44326. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44327. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44328. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44329. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44330. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44331. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44332. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44333. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44334. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44335. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44336. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44337. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44338. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44339. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44340. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44341. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44342. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44343. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44344. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44345. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44346. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44347. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44348. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44349. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44350. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44351. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44352. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44353. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44354. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44355. this._uniformBuffer.addUniform("pointSize", 1);
  44356. this._uniformBuffer.create();
  44357. };
  44358. /**
  44359. * Unbinds the textures.
  44360. */
  44361. PBRBaseMaterial.prototype.unbind = function () {
  44362. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44363. this._uniformBuffer.setTexture("reflectionSampler", null);
  44364. }
  44365. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44366. this._uniformBuffer.setTexture("refractionSampler", null);
  44367. }
  44368. _super.prototype.unbind.call(this);
  44369. };
  44370. /**
  44371. * Binds the submesh data.
  44372. * @param world - The world matrix.
  44373. * @param mesh - The BJS mesh.
  44374. * @param subMesh - A submesh of the BJS mesh.
  44375. */
  44376. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44377. var scene = this.getScene();
  44378. var defines = subMesh._materialDefines;
  44379. if (!defines) {
  44380. return;
  44381. }
  44382. var effect = subMesh.effect;
  44383. if (!effect) {
  44384. return;
  44385. }
  44386. this._activeEffect = effect;
  44387. // Matrices
  44388. this.bindOnlyWorldMatrix(world);
  44389. // Normal Matrix
  44390. if (defines.OBJECTSPACE_NORMALMAP) {
  44391. world.toNormalMatrix(this._normalMatrix);
  44392. this.bindOnlyNormalMatrix(this._normalMatrix);
  44393. }
  44394. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44395. // Bones
  44396. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44397. var reflectionTexture = null;
  44398. if (mustRebind) {
  44399. this._uniformBuffer.bindToEffect(effect, "Material");
  44400. this.bindViewProjection(effect);
  44401. reflectionTexture = this._getReflectionTexture();
  44402. var refractionTexture = this._getRefractionTexture();
  44403. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44404. // Texture uniforms
  44405. if (scene.texturesEnabled) {
  44406. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44407. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44408. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44409. }
  44410. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44411. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44412. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44413. }
  44414. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44415. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44416. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44417. }
  44418. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44419. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44420. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44421. if (reflectionTexture.boundingBoxSize) {
  44422. var cubeTexture = reflectionTexture;
  44423. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44424. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44425. }
  44426. var polynomials = reflectionTexture.sphericalPolynomial;
  44427. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44428. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44429. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44430. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44431. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44432. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44433. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44434. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44435. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44436. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44437. }
  44438. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44439. }
  44440. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44441. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44442. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44443. }
  44444. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44445. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44446. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44447. }
  44448. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44449. if (this._metallicTexture) {
  44450. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44451. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44452. }
  44453. else if (this._reflectivityTexture) {
  44454. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44455. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44456. }
  44457. if (this._microSurfaceTexture) {
  44458. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44459. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44460. }
  44461. }
  44462. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44463. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44464. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44465. if (scene._mirroredCameraPosition) {
  44466. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44467. }
  44468. else {
  44469. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44470. }
  44471. }
  44472. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44473. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44474. var depth = 1.0;
  44475. if (!refractionTexture.isCube) {
  44476. if (refractionTexture.depth) {
  44477. depth = refractionTexture.depth;
  44478. }
  44479. }
  44480. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44481. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44482. }
  44483. }
  44484. // Point size
  44485. if (this.pointsCloud) {
  44486. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44487. }
  44488. // Colors
  44489. if (defines.METALLICWORKFLOW) {
  44490. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44491. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44492. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44493. }
  44494. else {
  44495. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44496. }
  44497. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44498. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44499. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44500. // Misc
  44501. this._lightingInfos.x = this._directIntensity;
  44502. this._lightingInfos.y = this._emissiveIntensity;
  44503. this._lightingInfos.z = this._environmentIntensity;
  44504. this._lightingInfos.w = this._specularIntensity;
  44505. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44506. }
  44507. // Textures
  44508. if (scene.texturesEnabled) {
  44509. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44510. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44511. }
  44512. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44513. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44514. }
  44515. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44516. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44517. }
  44518. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44519. if (defines.LODBASEDMICROSFURACE) {
  44520. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44521. }
  44522. else {
  44523. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44524. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44525. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44526. }
  44527. }
  44528. if (defines.ENVIRONMENTBRDF) {
  44529. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44530. }
  44531. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44532. if (defines.LODBASEDMICROSFURACE) {
  44533. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44534. }
  44535. else {
  44536. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44537. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44538. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44539. }
  44540. }
  44541. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44542. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44543. }
  44544. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44545. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44546. }
  44547. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44548. if (this._metallicTexture) {
  44549. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44550. }
  44551. else if (this._reflectivityTexture) {
  44552. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44553. }
  44554. if (this._microSurfaceTexture) {
  44555. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44556. }
  44557. }
  44558. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44559. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44560. }
  44561. }
  44562. // Clip plane
  44563. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44564. // Colors
  44565. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44566. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44567. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44568. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44569. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44570. }
  44571. if (mustRebind || !this.isFrozen) {
  44572. // Lights
  44573. if (scene.lightsEnabled && !this._disableLighting) {
  44574. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44575. }
  44576. // View
  44577. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44578. this.bindView(effect);
  44579. }
  44580. // Fog
  44581. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44582. // Morph targets
  44583. if (defines.NUM_MORPH_INFLUENCERS) {
  44584. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44585. }
  44586. // image processing
  44587. this._imageProcessingConfiguration.bind(this._activeEffect);
  44588. // Log. depth
  44589. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44590. }
  44591. this._uniformBuffer.update();
  44592. this._afterBind(mesh, this._activeEffect);
  44593. };
  44594. /**
  44595. * Returns the animatable textures.
  44596. * @returns - Array of animatable textures.
  44597. */
  44598. PBRBaseMaterial.prototype.getAnimatables = function () {
  44599. var results = [];
  44600. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44601. results.push(this._albedoTexture);
  44602. }
  44603. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44604. results.push(this._ambientTexture);
  44605. }
  44606. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44607. results.push(this._opacityTexture);
  44608. }
  44609. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44610. results.push(this._reflectionTexture);
  44611. }
  44612. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44613. results.push(this._emissiveTexture);
  44614. }
  44615. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44616. results.push(this._metallicTexture);
  44617. }
  44618. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44619. results.push(this._reflectivityTexture);
  44620. }
  44621. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44622. results.push(this._bumpTexture);
  44623. }
  44624. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44625. results.push(this._lightmapTexture);
  44626. }
  44627. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44628. results.push(this._refractionTexture);
  44629. }
  44630. return results;
  44631. };
  44632. /**
  44633. * Returns the texture used for reflections.
  44634. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44635. */
  44636. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44637. if (this._reflectionTexture) {
  44638. return this._reflectionTexture;
  44639. }
  44640. return this.getScene().environmentTexture;
  44641. };
  44642. /**
  44643. * Returns the texture used for refraction or null if none is used.
  44644. * @returns - Refection texture if present. If no refraction texture and refraction
  44645. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44646. */
  44647. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44648. if (this._refractionTexture) {
  44649. return this._refractionTexture;
  44650. }
  44651. if (this._linkRefractionWithTransparency) {
  44652. return this.getScene().environmentTexture;
  44653. }
  44654. return null;
  44655. };
  44656. /**
  44657. * Disposes the resources of the material.
  44658. * @param forceDisposeEffect - Forces the disposal of effects.
  44659. * @param forceDisposeTextures - Forces the disposal of all textures.
  44660. */
  44661. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44662. if (forceDisposeTextures) {
  44663. if (this._albedoTexture) {
  44664. this._albedoTexture.dispose();
  44665. }
  44666. if (this._ambientTexture) {
  44667. this._ambientTexture.dispose();
  44668. }
  44669. if (this._opacityTexture) {
  44670. this._opacityTexture.dispose();
  44671. }
  44672. if (this._reflectionTexture) {
  44673. this._reflectionTexture.dispose();
  44674. }
  44675. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44676. this._environmentBRDFTexture.dispose();
  44677. }
  44678. if (this._emissiveTexture) {
  44679. this._emissiveTexture.dispose();
  44680. }
  44681. if (this._metallicTexture) {
  44682. this._metallicTexture.dispose();
  44683. }
  44684. if (this._reflectivityTexture) {
  44685. this._reflectivityTexture.dispose();
  44686. }
  44687. if (this._bumpTexture) {
  44688. this._bumpTexture.dispose();
  44689. }
  44690. if (this._lightmapTexture) {
  44691. this._lightmapTexture.dispose();
  44692. }
  44693. if (this._refractionTexture) {
  44694. this._refractionTexture.dispose();
  44695. }
  44696. }
  44697. this._renderTargets.dispose();
  44698. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44699. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44700. }
  44701. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44702. };
  44703. /**
  44704. * Stores the reflectivity values based on metallic roughness workflow.
  44705. */
  44706. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44707. __decorate([
  44708. BABYLON.serializeAsImageProcessingConfiguration()
  44709. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44710. __decorate([
  44711. BABYLON.serialize()
  44712. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44713. __decorate([
  44714. BABYLON.serialize()
  44715. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44716. return PBRBaseMaterial;
  44717. }(BABYLON.PushMaterial));
  44718. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44719. })(BABYLON || (BABYLON = {}));
  44720. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44721. var BABYLON;
  44722. (function (BABYLON) {
  44723. /**
  44724. * The Physically based simple base material of BJS.
  44725. *
  44726. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44727. * It is used as the base class for both the specGloss and metalRough conventions.
  44728. */
  44729. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44730. __extends(PBRBaseSimpleMaterial, _super);
  44731. /**
  44732. * Instantiates a new PBRMaterial instance.
  44733. *
  44734. * @param name The material name
  44735. * @param scene The scene the material will be use in.
  44736. */
  44737. function PBRBaseSimpleMaterial(name, scene) {
  44738. var _this = _super.call(this, name, scene) || this;
  44739. /**
  44740. * Number of Simultaneous lights allowed on the material.
  44741. */
  44742. _this.maxSimultaneousLights = 4;
  44743. /**
  44744. * If sets to true, disables all the lights affecting the material.
  44745. */
  44746. _this.disableLighting = false;
  44747. /**
  44748. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44749. */
  44750. _this.invertNormalMapX = false;
  44751. /**
  44752. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44753. */
  44754. _this.invertNormalMapY = false;
  44755. /**
  44756. * Emissivie color used to self-illuminate the model.
  44757. */
  44758. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44759. /**
  44760. * Occlusion Channel Strenght.
  44761. */
  44762. _this.occlusionStrength = 1.0;
  44763. _this.useLightmapAsShadowmap = false;
  44764. _this._useAlphaFromAlbedoTexture = true;
  44765. _this._useAmbientInGrayScale = true;
  44766. return _this;
  44767. }
  44768. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44769. /**
  44770. * Gets the current double sided mode.
  44771. */
  44772. get: function () {
  44773. return this._twoSidedLighting;
  44774. },
  44775. /**
  44776. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44777. */
  44778. set: function (value) {
  44779. if (this._twoSidedLighting === value) {
  44780. return;
  44781. }
  44782. this._twoSidedLighting = value;
  44783. this.backFaceCulling = !value;
  44784. this._markAllSubMeshesAsTexturesDirty();
  44785. },
  44786. enumerable: true,
  44787. configurable: true
  44788. });
  44789. /**
  44790. * Return the active textures of the material.
  44791. */
  44792. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44793. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44794. if (this.environmentTexture) {
  44795. activeTextures.push(this.environmentTexture);
  44796. }
  44797. if (this.normalTexture) {
  44798. activeTextures.push(this.normalTexture);
  44799. }
  44800. if (this.emissiveTexture) {
  44801. activeTextures.push(this.emissiveTexture);
  44802. }
  44803. if (this.occlusionTexture) {
  44804. activeTextures.push(this.occlusionTexture);
  44805. }
  44806. if (this.lightmapTexture) {
  44807. activeTextures.push(this.lightmapTexture);
  44808. }
  44809. return activeTextures;
  44810. };
  44811. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44812. if (_super.prototype.hasTexture.call(this, texture)) {
  44813. return true;
  44814. }
  44815. if (this.lightmapTexture === texture) {
  44816. return true;
  44817. }
  44818. return false;
  44819. };
  44820. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44821. return "PBRBaseSimpleMaterial";
  44822. };
  44823. __decorate([
  44824. BABYLON.serialize(),
  44825. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44826. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44827. __decorate([
  44828. BABYLON.serialize(),
  44829. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44830. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44831. __decorate([
  44832. BABYLON.serializeAsTexture(),
  44833. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44834. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44835. __decorate([
  44836. BABYLON.serialize(),
  44837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44838. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44839. __decorate([
  44840. BABYLON.serialize(),
  44841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44842. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44843. __decorate([
  44844. BABYLON.serializeAsTexture(),
  44845. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44846. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44847. __decorate([
  44848. BABYLON.serializeAsColor3("emissive"),
  44849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44850. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44851. __decorate([
  44852. BABYLON.serializeAsTexture(),
  44853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44854. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44855. __decorate([
  44856. BABYLON.serialize(),
  44857. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44858. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44859. __decorate([
  44860. BABYLON.serializeAsTexture(),
  44861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44862. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44863. __decorate([
  44864. BABYLON.serialize(),
  44865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44866. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44867. __decorate([
  44868. BABYLON.serialize()
  44869. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44870. __decorate([
  44871. BABYLON.serializeAsTexture(),
  44872. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44873. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44874. __decorate([
  44875. BABYLON.serialize(),
  44876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44877. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44878. return PBRBaseSimpleMaterial;
  44879. }(BABYLON.PBRBaseMaterial));
  44880. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44881. })(BABYLON || (BABYLON = {}));
  44882. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44883. var BABYLON;
  44884. (function (BABYLON) {
  44885. /**
  44886. * The Physically based material of BJS.
  44887. *
  44888. * This offers the main features of a standard PBR material.
  44889. * For more information, please refer to the documentation :
  44890. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44891. */
  44892. var PBRMaterial = /** @class */ (function (_super) {
  44893. __extends(PBRMaterial, _super);
  44894. /**
  44895. * Instantiates a new PBRMaterial instance.
  44896. *
  44897. * @param name The material name
  44898. * @param scene The scene the material will be use in.
  44899. */
  44900. function PBRMaterial(name, scene) {
  44901. var _this = _super.call(this, name, scene) || this;
  44902. /**
  44903. * Intensity of the direct lights e.g. the four lights available in your scene.
  44904. * This impacts both the direct diffuse and specular highlights.
  44905. */
  44906. _this.directIntensity = 1.0;
  44907. /**
  44908. * Intensity of the emissive part of the material.
  44909. * This helps controlling the emissive effect without modifying the emissive color.
  44910. */
  44911. _this.emissiveIntensity = 1.0;
  44912. /**
  44913. * Intensity of the environment e.g. how much the environment will light the object
  44914. * either through harmonics for rough material or through the refelction for shiny ones.
  44915. */
  44916. _this.environmentIntensity = 1.0;
  44917. /**
  44918. * This is a special control allowing the reduction of the specular highlights coming from the
  44919. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44920. */
  44921. _this.specularIntensity = 1.0;
  44922. /**
  44923. * Debug Control allowing disabling the bump map on this material.
  44924. */
  44925. _this.disableBumpMap = false;
  44926. /**
  44927. * AKA Occlusion Texture Intensity in other nomenclature.
  44928. */
  44929. _this.ambientTextureStrength = 1.0;
  44930. /**
  44931. * The color of a material in ambient lighting.
  44932. */
  44933. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  44934. /**
  44935. * AKA Diffuse Color in other nomenclature.
  44936. */
  44937. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  44938. /**
  44939. * AKA Specular Color in other nomenclature.
  44940. */
  44941. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44942. /**
  44943. * The color reflected from the material.
  44944. */
  44945. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  44946. /**
  44947. * The color emitted from the material.
  44948. */
  44949. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44950. /**
  44951. * AKA Glossiness in other nomenclature.
  44952. */
  44953. _this.microSurface = 1.0;
  44954. /**
  44955. * source material index of refraction (IOR)' / 'destination material IOR.
  44956. */
  44957. _this.indexOfRefraction = 0.66;
  44958. /**
  44959. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44960. */
  44961. _this.invertRefractionY = false;
  44962. /**
  44963. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44964. * Materials half opaque for instance using refraction could benefit from this control.
  44965. */
  44966. _this.linkRefractionWithTransparency = false;
  44967. _this.useLightmapAsShadowmap = false;
  44968. /**
  44969. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44970. */
  44971. _this.useAlphaFromAlbedoTexture = false;
  44972. /**
  44973. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44974. */
  44975. _this.forceAlphaTest = false;
  44976. /**
  44977. * Defines the alpha limits in alpha test mode.
  44978. */
  44979. _this.alphaCutOff = 0.4;
  44980. /**
  44981. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44982. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44983. */
  44984. _this.useSpecularOverAlpha = true;
  44985. /**
  44986. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44987. */
  44988. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  44989. /**
  44990. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44991. */
  44992. _this.useRoughnessFromMetallicTextureAlpha = true;
  44993. /**
  44994. * Specifies if the metallic texture contains the roughness information in its green channel.
  44995. */
  44996. _this.useRoughnessFromMetallicTextureGreen = false;
  44997. /**
  44998. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44999. */
  45000. _this.useMetallnessFromMetallicTextureBlue = false;
  45001. /**
  45002. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45003. */
  45004. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45005. /**
  45006. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45007. */
  45008. _this.useAmbientInGrayScale = false;
  45009. /**
  45010. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45011. * The material will try to infer what glossiness each pixel should be.
  45012. */
  45013. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45014. /**
  45015. * BJS is using an harcoded light falloff based on a manually sets up range.
  45016. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45017. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45018. */
  45019. _this.usePhysicalLightFalloff = true;
  45020. /**
  45021. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45022. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45023. */
  45024. _this.useRadianceOverAlpha = true;
  45025. /**
  45026. * Allows using an object space normal map (instead of tangent space).
  45027. */
  45028. _this.useObjectSpaceNormalMap = false;
  45029. /**
  45030. * Allows using the bump map in parallax mode.
  45031. */
  45032. _this.useParallax = false;
  45033. /**
  45034. * Allows using the bump map in parallax occlusion mode.
  45035. */
  45036. _this.useParallaxOcclusion = false;
  45037. /**
  45038. * Controls the scale bias of the parallax mode.
  45039. */
  45040. _this.parallaxScaleBias = 0.05;
  45041. /**
  45042. * If sets to true, disables all the lights affecting the material.
  45043. */
  45044. _this.disableLighting = false;
  45045. /**
  45046. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45047. */
  45048. _this.forceIrradianceInFragment = false;
  45049. /**
  45050. * Number of Simultaneous lights allowed on the material.
  45051. */
  45052. _this.maxSimultaneousLights = 4;
  45053. /**
  45054. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45055. */
  45056. _this.invertNormalMapX = false;
  45057. /**
  45058. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45059. */
  45060. _this.invertNormalMapY = false;
  45061. /**
  45062. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45063. */
  45064. _this.twoSidedLighting = false;
  45065. /**
  45066. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45067. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45068. */
  45069. _this.useAlphaFresnel = false;
  45070. /**
  45071. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45072. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45073. */
  45074. _this.useLinearAlphaFresnel = false;
  45075. /**
  45076. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45077. * And/Or occlude the blended part.
  45078. */
  45079. _this.environmentBRDFTexture = null;
  45080. /**
  45081. * Force normal to face away from face.
  45082. */
  45083. _this.forceNormalForward = false;
  45084. /**
  45085. * Enables specular anti aliasing in the PBR shader.
  45086. * It will both interacts on the Geometry for analytical and IBL lighting.
  45087. * It also prefilter the roughness map based on the bump values.
  45088. */
  45089. _this.enableSpecularAntiAliasing = false;
  45090. /**
  45091. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45092. * makes the reflect vector face the model (under horizon).
  45093. */
  45094. _this.useHorizonOcclusion = true;
  45095. /**
  45096. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45097. * too much the area relying on ambient texture to define their ambient occlusion.
  45098. */
  45099. _this.useRadianceOcclusion = true;
  45100. /**
  45101. * If set to true, no lighting calculations will be applied.
  45102. */
  45103. _this.unlit = false;
  45104. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45105. return _this;
  45106. }
  45107. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45108. /**
  45109. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45110. */
  45111. get: function () {
  45112. return this._PBRMATERIAL_OPAQUE;
  45113. },
  45114. enumerable: true,
  45115. configurable: true
  45116. });
  45117. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45118. /**
  45119. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45120. */
  45121. get: function () {
  45122. return this._PBRMATERIAL_ALPHATEST;
  45123. },
  45124. enumerable: true,
  45125. configurable: true
  45126. });
  45127. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45128. /**
  45129. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45130. */
  45131. get: function () {
  45132. return this._PBRMATERIAL_ALPHABLEND;
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45138. /**
  45139. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45140. * They are also discarded below the alpha cutoff threshold to improve performances.
  45141. */
  45142. get: function () {
  45143. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45144. },
  45145. enumerable: true,
  45146. configurable: true
  45147. });
  45148. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45149. /**
  45150. * Gets the image processing configuration used either in this material.
  45151. */
  45152. get: function () {
  45153. return this._imageProcessingConfiguration;
  45154. },
  45155. /**
  45156. * Sets the Default image processing configuration used either in the this material.
  45157. *
  45158. * If sets to null, the scene one is in use.
  45159. */
  45160. set: function (value) {
  45161. this._attachImageProcessingConfiguration(value);
  45162. // Ensure the effect will be rebuilt.
  45163. this._markAllSubMeshesAsTexturesDirty();
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45169. /**
  45170. * Gets wether the color curves effect is enabled.
  45171. */
  45172. get: function () {
  45173. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45174. },
  45175. /**
  45176. * Sets wether the color curves effect is enabled.
  45177. */
  45178. set: function (value) {
  45179. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45180. },
  45181. enumerable: true,
  45182. configurable: true
  45183. });
  45184. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45185. /**
  45186. * Gets wether the color grading effect is enabled.
  45187. */
  45188. get: function () {
  45189. return this.imageProcessingConfiguration.colorGradingEnabled;
  45190. },
  45191. /**
  45192. * Gets wether the color grading effect is enabled.
  45193. */
  45194. set: function (value) {
  45195. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45201. /**
  45202. * Gets wether tonemapping is enabled or not.
  45203. */
  45204. get: function () {
  45205. return this._imageProcessingConfiguration.toneMappingEnabled;
  45206. },
  45207. /**
  45208. * Sets wether tonemapping is enabled or not
  45209. */
  45210. set: function (value) {
  45211. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. ;
  45217. ;
  45218. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45219. /**
  45220. * The camera exposure used on this material.
  45221. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45222. * This corresponds to a photographic exposure.
  45223. */
  45224. get: function () {
  45225. return this._imageProcessingConfiguration.exposure;
  45226. },
  45227. /**
  45228. * The camera exposure used on this material.
  45229. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45230. * This corresponds to a photographic exposure.
  45231. */
  45232. set: function (value) {
  45233. this._imageProcessingConfiguration.exposure = value;
  45234. },
  45235. enumerable: true,
  45236. configurable: true
  45237. });
  45238. ;
  45239. ;
  45240. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45241. /**
  45242. * Gets The camera contrast used on this material.
  45243. */
  45244. get: function () {
  45245. return this._imageProcessingConfiguration.contrast;
  45246. },
  45247. /**
  45248. * Sets The camera contrast used on this material.
  45249. */
  45250. set: function (value) {
  45251. this._imageProcessingConfiguration.contrast = value;
  45252. },
  45253. enumerable: true,
  45254. configurable: true
  45255. });
  45256. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45257. /**
  45258. * Gets the Color Grading 2D Lookup Texture.
  45259. */
  45260. get: function () {
  45261. return this._imageProcessingConfiguration.colorGradingTexture;
  45262. },
  45263. /**
  45264. * Sets the Color Grading 2D Lookup Texture.
  45265. */
  45266. set: function (value) {
  45267. this._imageProcessingConfiguration.colorGradingTexture = value;
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45273. /**
  45274. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45275. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45276. * 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;
  45277. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45278. */
  45279. get: function () {
  45280. return this._imageProcessingConfiguration.colorCurves;
  45281. },
  45282. /**
  45283. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45284. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45285. * 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;
  45286. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45287. */
  45288. set: function (value) {
  45289. this._imageProcessingConfiguration.colorCurves = value;
  45290. },
  45291. enumerable: true,
  45292. configurable: true
  45293. });
  45294. /**
  45295. * Returns the name of this material class.
  45296. */
  45297. PBRMaterial.prototype.getClassName = function () {
  45298. return "PBRMaterial";
  45299. };
  45300. /**
  45301. * Returns an array of the actively used textures.
  45302. * @returns - Array of BaseTextures
  45303. */
  45304. PBRMaterial.prototype.getActiveTextures = function () {
  45305. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45306. if (this._albedoTexture) {
  45307. activeTextures.push(this._albedoTexture);
  45308. }
  45309. if (this._ambientTexture) {
  45310. activeTextures.push(this._ambientTexture);
  45311. }
  45312. if (this._opacityTexture) {
  45313. activeTextures.push(this._opacityTexture);
  45314. }
  45315. if (this._reflectionTexture) {
  45316. activeTextures.push(this._reflectionTexture);
  45317. }
  45318. if (this._emissiveTexture) {
  45319. activeTextures.push(this._emissiveTexture);
  45320. }
  45321. if (this._reflectivityTexture) {
  45322. activeTextures.push(this._reflectivityTexture);
  45323. }
  45324. if (this._metallicTexture) {
  45325. activeTextures.push(this._metallicTexture);
  45326. }
  45327. if (this._microSurfaceTexture) {
  45328. activeTextures.push(this._microSurfaceTexture);
  45329. }
  45330. if (this._bumpTexture) {
  45331. activeTextures.push(this._bumpTexture);
  45332. }
  45333. if (this._lightmapTexture) {
  45334. activeTextures.push(this._lightmapTexture);
  45335. }
  45336. if (this._refractionTexture) {
  45337. activeTextures.push(this._refractionTexture);
  45338. }
  45339. return activeTextures;
  45340. };
  45341. /**
  45342. * Checks to see if a texture is used in the material.
  45343. * @param texture - Base texture to use.
  45344. * @returns - Boolean specifying if a texture is used in the material.
  45345. */
  45346. PBRMaterial.prototype.hasTexture = function (texture) {
  45347. if (_super.prototype.hasTexture.call(this, texture)) {
  45348. return true;
  45349. }
  45350. if (this._albedoTexture === texture) {
  45351. return true;
  45352. }
  45353. if (this._ambientTexture === texture) {
  45354. return true;
  45355. }
  45356. if (this._opacityTexture === texture) {
  45357. return true;
  45358. }
  45359. if (this._reflectionTexture === texture) {
  45360. return true;
  45361. }
  45362. if (this._reflectivityTexture === texture) {
  45363. return true;
  45364. }
  45365. if (this._metallicTexture === texture) {
  45366. return true;
  45367. }
  45368. if (this._microSurfaceTexture === texture) {
  45369. return true;
  45370. }
  45371. if (this._bumpTexture === texture) {
  45372. return true;
  45373. }
  45374. if (this._lightmapTexture === texture) {
  45375. return true;
  45376. }
  45377. if (this._refractionTexture === texture) {
  45378. return true;
  45379. }
  45380. return false;
  45381. };
  45382. /**
  45383. * Makes a duplicate of the current material.
  45384. * @param name - name to use for the new material.
  45385. */
  45386. PBRMaterial.prototype.clone = function (name) {
  45387. var _this = this;
  45388. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45389. clone.id = name;
  45390. clone.name = name;
  45391. return clone;
  45392. };
  45393. /**
  45394. * Serializes this PBR Material.
  45395. * @returns - An object with the serialized material.
  45396. */
  45397. PBRMaterial.prototype.serialize = function () {
  45398. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45399. serializationObject.customType = "BABYLON.PBRMaterial";
  45400. return serializationObject;
  45401. };
  45402. // Statics
  45403. /**
  45404. * Parses a PBR Material from a serialized object.
  45405. * @param source - Serialized object.
  45406. * @param scene - BJS scene instance.
  45407. * @param rootUrl - url for the scene object
  45408. * @returns - PBRMaterial
  45409. */
  45410. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45411. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45412. };
  45413. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45414. /**
  45415. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45416. */
  45417. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45418. /**
  45419. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45420. */
  45421. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45422. /**
  45423. * Represents the value for Alpha Test and Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45424. * They are also discarded below the alpha cutoff threshold to improve performances.
  45425. */
  45426. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45427. __decorate([
  45428. BABYLON.serialize(),
  45429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45430. ], PBRMaterial.prototype, "directIntensity", void 0);
  45431. __decorate([
  45432. BABYLON.serialize(),
  45433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45434. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45435. __decorate([
  45436. BABYLON.serialize(),
  45437. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45438. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45439. __decorate([
  45440. BABYLON.serialize(),
  45441. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45442. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45443. __decorate([
  45444. BABYLON.serialize(),
  45445. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45446. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45447. __decorate([
  45448. BABYLON.serializeAsTexture(),
  45449. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45450. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45451. __decorate([
  45452. BABYLON.serializeAsTexture(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45454. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45459. __decorate([
  45460. BABYLON.serializeAsTexture(),
  45461. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45462. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45463. __decorate([
  45464. BABYLON.serializeAsTexture(),
  45465. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45466. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45467. __decorate([
  45468. BABYLON.serializeAsTexture(),
  45469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45470. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45471. __decorate([
  45472. BABYLON.serializeAsTexture(),
  45473. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45474. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45475. __decorate([
  45476. BABYLON.serializeAsTexture(),
  45477. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45478. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45479. __decorate([
  45480. BABYLON.serialize(),
  45481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45482. ], PBRMaterial.prototype, "metallic", void 0);
  45483. __decorate([
  45484. BABYLON.serialize(),
  45485. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45486. ], PBRMaterial.prototype, "roughness", void 0);
  45487. __decorate([
  45488. BABYLON.serializeAsTexture(),
  45489. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45490. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45491. __decorate([
  45492. BABYLON.serializeAsTexture(),
  45493. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45494. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45495. __decorate([
  45496. BABYLON.serializeAsTexture(),
  45497. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45498. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45499. __decorate([
  45500. BABYLON.serializeAsTexture(),
  45501. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45502. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45503. __decorate([
  45504. BABYLON.serializeAsColor3("ambient"),
  45505. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45506. ], PBRMaterial.prototype, "ambientColor", void 0);
  45507. __decorate([
  45508. BABYLON.serializeAsColor3("albedo"),
  45509. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45510. ], PBRMaterial.prototype, "albedoColor", void 0);
  45511. __decorate([
  45512. BABYLON.serializeAsColor3("reflectivity"),
  45513. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45514. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45515. __decorate([
  45516. BABYLON.serializeAsColor3("reflection"),
  45517. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45518. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45519. __decorate([
  45520. BABYLON.serializeAsColor3("emissive"),
  45521. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45522. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45523. __decorate([
  45524. BABYLON.serialize(),
  45525. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45526. ], PBRMaterial.prototype, "microSurface", void 0);
  45527. __decorate([
  45528. BABYLON.serialize(),
  45529. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45530. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45531. __decorate([
  45532. BABYLON.serialize(),
  45533. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45534. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45535. __decorate([
  45536. BABYLON.serialize(),
  45537. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45538. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45539. __decorate([
  45540. BABYLON.serialize(),
  45541. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45542. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45543. __decorate([
  45544. BABYLON.serialize(),
  45545. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45546. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45547. __decorate([
  45548. BABYLON.serialize(),
  45549. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45550. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45551. __decorate([
  45552. BABYLON.serialize(),
  45553. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45554. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45555. __decorate([
  45556. BABYLON.serialize(),
  45557. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45558. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45559. __decorate([
  45560. BABYLON.serialize(),
  45561. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45562. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45563. __decorate([
  45564. BABYLON.serialize(),
  45565. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45566. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45567. __decorate([
  45568. BABYLON.serialize(),
  45569. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45570. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45571. __decorate([
  45572. BABYLON.serialize(),
  45573. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45574. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45575. __decorate([
  45576. BABYLON.serialize(),
  45577. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45578. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45579. __decorate([
  45580. BABYLON.serialize(),
  45581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45582. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45583. __decorate([
  45584. BABYLON.serialize(),
  45585. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45586. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45587. __decorate([
  45588. BABYLON.serialize(),
  45589. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45590. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45591. __decorate([
  45592. BABYLON.serialize(),
  45593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45594. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45598. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45602. ], PBRMaterial.prototype, "useParallax", void 0);
  45603. __decorate([
  45604. BABYLON.serialize(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45606. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45614. ], PBRMaterial.prototype, "disableLighting", void 0);
  45615. __decorate([
  45616. BABYLON.serialize(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45618. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45619. __decorate([
  45620. BABYLON.serialize(),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45622. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45623. __decorate([
  45624. BABYLON.serialize(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45630. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45631. __decorate([
  45632. BABYLON.serialize(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45634. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45638. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45639. __decorate([
  45640. BABYLON.serialize(),
  45641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45642. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45643. __decorate([
  45644. BABYLON.serializeAsTexture(),
  45645. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45646. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45647. __decorate([
  45648. BABYLON.serialize(),
  45649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45650. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45651. __decorate([
  45652. BABYLON.serialize(),
  45653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45654. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45655. __decorate([
  45656. BABYLON.serialize(),
  45657. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45658. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45659. __decorate([
  45660. BABYLON.serialize(),
  45661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45662. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45663. __decorate([
  45664. BABYLON.serialize(),
  45665. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45666. ], PBRMaterial.prototype, "unlit", void 0);
  45667. return PBRMaterial;
  45668. }(BABYLON.PBRBaseMaterial));
  45669. BABYLON.PBRMaterial = PBRMaterial;
  45670. })(BABYLON || (BABYLON = {}));
  45671. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45672. var BABYLON;
  45673. (function (BABYLON) {
  45674. /**
  45675. * The PBR material of BJS following the metal roughness convention.
  45676. *
  45677. * This fits to the PBR convention in the GLTF definition:
  45678. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45679. */
  45680. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45681. __extends(PBRMetallicRoughnessMaterial, _super);
  45682. /**
  45683. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45684. *
  45685. * @param name The material name
  45686. * @param scene The scene the material will be use in.
  45687. */
  45688. function PBRMetallicRoughnessMaterial(name, scene) {
  45689. var _this = _super.call(this, name, scene) || this;
  45690. _this._useRoughnessFromMetallicTextureAlpha = false;
  45691. _this._useRoughnessFromMetallicTextureGreen = true;
  45692. _this._useMetallnessFromMetallicTextureBlue = true;
  45693. _this.metallic = 1.0;
  45694. _this.roughness = 1.0;
  45695. return _this;
  45696. }
  45697. /**
  45698. * Return the currrent class name of the material.
  45699. */
  45700. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45701. return "PBRMetallicRoughnessMaterial";
  45702. };
  45703. /**
  45704. * Return the active textures of the material.
  45705. */
  45706. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45707. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45708. if (this.baseTexture) {
  45709. activeTextures.push(this.baseTexture);
  45710. }
  45711. if (this.metallicRoughnessTexture) {
  45712. activeTextures.push(this.metallicRoughnessTexture);
  45713. }
  45714. return activeTextures;
  45715. };
  45716. /**
  45717. * Checks to see if a texture is used in the material.
  45718. * @param texture - Base texture to use.
  45719. * @returns - Boolean specifying if a texture is used in the material.
  45720. */
  45721. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45722. if (_super.prototype.hasTexture.call(this, texture)) {
  45723. return true;
  45724. }
  45725. if (this.baseTexture === texture) {
  45726. return true;
  45727. }
  45728. if (this.metallicRoughnessTexture === texture) {
  45729. return true;
  45730. }
  45731. return false;
  45732. };
  45733. /**
  45734. * Makes a duplicate of the current material.
  45735. * @param name - name to use for the new material.
  45736. */
  45737. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45738. var _this = this;
  45739. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45740. clone.id = name;
  45741. clone.name = name;
  45742. return clone;
  45743. };
  45744. /**
  45745. * Serialize the material to a parsable JSON object.
  45746. */
  45747. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45748. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45749. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45750. return serializationObject;
  45751. };
  45752. /**
  45753. * Parses a JSON object correponding to the serialize function.
  45754. */
  45755. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45756. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45757. };
  45758. __decorate([
  45759. BABYLON.serializeAsColor3(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45761. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45762. __decorate([
  45763. BABYLON.serializeAsTexture(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45765. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45773. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45774. __decorate([
  45775. BABYLON.serializeAsTexture(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45777. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45778. return PBRMetallicRoughnessMaterial;
  45779. }(BABYLON.PBRBaseSimpleMaterial));
  45780. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45781. })(BABYLON || (BABYLON = {}));
  45782. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45783. var BABYLON;
  45784. (function (BABYLON) {
  45785. /**
  45786. * The PBR material of BJS following the specular glossiness convention.
  45787. *
  45788. * This fits to the PBR convention in the GLTF definition:
  45789. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45790. */
  45791. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45792. __extends(PBRSpecularGlossinessMaterial, _super);
  45793. /**
  45794. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45795. *
  45796. * @param name The material name
  45797. * @param scene The scene the material will be use in.
  45798. */
  45799. function PBRSpecularGlossinessMaterial(name, scene) {
  45800. var _this = _super.call(this, name, scene) || this;
  45801. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45802. return _this;
  45803. }
  45804. /**
  45805. * Return the currrent class name of the material.
  45806. */
  45807. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45808. return "PBRSpecularGlossinessMaterial";
  45809. };
  45810. /**
  45811. * Return the active textures of the material.
  45812. */
  45813. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45814. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45815. if (this.diffuseTexture) {
  45816. activeTextures.push(this.diffuseTexture);
  45817. }
  45818. if (this.specularGlossinessTexture) {
  45819. activeTextures.push(this.specularGlossinessTexture);
  45820. }
  45821. return activeTextures;
  45822. };
  45823. /**
  45824. * Checks to see if a texture is used in the material.
  45825. * @param texture - Base texture to use.
  45826. * @returns - Boolean specifying if a texture is used in the material.
  45827. */
  45828. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45829. if (_super.prototype.hasTexture.call(this, texture)) {
  45830. return true;
  45831. }
  45832. if (this.diffuseTexture === texture) {
  45833. return true;
  45834. }
  45835. if (this.specularGlossinessTexture === texture) {
  45836. return true;
  45837. }
  45838. return false;
  45839. };
  45840. /**
  45841. * Makes a duplicate of the current material.
  45842. * @param name - name to use for the new material.
  45843. */
  45844. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45845. var _this = this;
  45846. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45847. clone.id = name;
  45848. clone.name = name;
  45849. return clone;
  45850. };
  45851. /**
  45852. * Serialize the material to a parsable JSON object.
  45853. */
  45854. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45855. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45856. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45857. return serializationObject;
  45858. };
  45859. /**
  45860. * Parses a JSON object correponding to the serialize function.
  45861. */
  45862. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45863. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45864. };
  45865. __decorate([
  45866. BABYLON.serializeAsColor3("diffuse"),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45868. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45869. __decorate([
  45870. BABYLON.serializeAsTexture(),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45872. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45873. __decorate([
  45874. BABYLON.serializeAsColor3("specular"),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45876. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45877. __decorate([
  45878. BABYLON.serialize(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45880. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45881. __decorate([
  45882. BABYLON.serializeAsTexture(),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45884. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45885. return PBRSpecularGlossinessMaterial;
  45886. }(BABYLON.PBRBaseSimpleMaterial));
  45887. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45888. })(BABYLON || (BABYLON = {}));
  45889. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45890. var BABYLON;
  45891. (function (BABYLON) {
  45892. BABYLON.CameraInputTypes = {};
  45893. var CameraInputsManager = /** @class */ (function () {
  45894. function CameraInputsManager(camera) {
  45895. this.attached = {};
  45896. this.camera = camera;
  45897. this.checkInputs = function () { };
  45898. }
  45899. /**
  45900. * Add an input method to a camera.
  45901. * builtin inputs example: camera.inputs.addGamepad();
  45902. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45903. * @param input camera input method
  45904. */
  45905. CameraInputsManager.prototype.add = function (input) {
  45906. var type = input.getSimpleName();
  45907. if (this.attached[type]) {
  45908. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45909. return;
  45910. }
  45911. this.attached[type] = input;
  45912. input.camera = this.camera;
  45913. //for checkInputs, we are dynamically creating a function
  45914. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45915. if (input.checkInputs) {
  45916. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45917. }
  45918. if (this.attachedElement) {
  45919. input.attachControl(this.attachedElement);
  45920. }
  45921. };
  45922. /**
  45923. * Remove a specific input method from a camera
  45924. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  45925. * @param inputToRemove camera input method
  45926. */
  45927. CameraInputsManager.prototype.remove = function (inputToRemove) {
  45928. for (var cam in this.attached) {
  45929. var input = this.attached[cam];
  45930. if (input === inputToRemove) {
  45931. input.detachControl(this.attachedElement);
  45932. input.camera = null;
  45933. delete this.attached[cam];
  45934. this.rebuildInputCheck();
  45935. }
  45936. }
  45937. };
  45938. CameraInputsManager.prototype.removeByType = function (inputType) {
  45939. for (var cam in this.attached) {
  45940. var input = this.attached[cam];
  45941. if (input.getClassName() === inputType) {
  45942. input.detachControl(this.attachedElement);
  45943. input.camera = null;
  45944. delete this.attached[cam];
  45945. this.rebuildInputCheck();
  45946. }
  45947. }
  45948. };
  45949. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  45950. var current = this.checkInputs;
  45951. return function () {
  45952. current();
  45953. fn();
  45954. };
  45955. };
  45956. CameraInputsManager.prototype.attachInput = function (input) {
  45957. if (this.attachedElement) {
  45958. input.attachControl(this.attachedElement, this.noPreventDefault);
  45959. }
  45960. };
  45961. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  45962. if (noPreventDefault === void 0) { noPreventDefault = false; }
  45963. if (this.attachedElement) {
  45964. return;
  45965. }
  45966. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45967. this.attachedElement = element;
  45968. this.noPreventDefault = noPreventDefault;
  45969. for (var cam in this.attached) {
  45970. this.attached[cam].attachControl(element, noPreventDefault);
  45971. }
  45972. };
  45973. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  45974. if (disconnect === void 0) { disconnect = false; }
  45975. if (this.attachedElement !== element) {
  45976. return;
  45977. }
  45978. for (var cam in this.attached) {
  45979. this.attached[cam].detachControl(element);
  45980. if (disconnect) {
  45981. this.attached[cam].camera = null;
  45982. }
  45983. }
  45984. this.attachedElement = null;
  45985. };
  45986. CameraInputsManager.prototype.rebuildInputCheck = function () {
  45987. this.checkInputs = function () { };
  45988. for (var cam in this.attached) {
  45989. var input = this.attached[cam];
  45990. if (input.checkInputs) {
  45991. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  45992. }
  45993. }
  45994. };
  45995. /**
  45996. * Remove all attached input methods from a camera
  45997. */
  45998. CameraInputsManager.prototype.clear = function () {
  45999. if (this.attachedElement) {
  46000. this.detachElement(this.attachedElement, true);
  46001. }
  46002. this.attached = {};
  46003. this.attachedElement = null;
  46004. this.checkInputs = function () { };
  46005. };
  46006. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46007. var inputs = {};
  46008. for (var cam in this.attached) {
  46009. var input = this.attached[cam];
  46010. var res = BABYLON.SerializationHelper.Serialize(input);
  46011. inputs[input.getClassName()] = res;
  46012. }
  46013. serializedCamera.inputsmgr = inputs;
  46014. };
  46015. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46016. var parsedInputs = parsedCamera.inputsmgr;
  46017. if (parsedInputs) {
  46018. this.clear();
  46019. for (var n in parsedInputs) {
  46020. var construct = BABYLON.CameraInputTypes[n];
  46021. if (construct) {
  46022. var parsedinput = parsedInputs[n];
  46023. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46024. this.add(input);
  46025. }
  46026. }
  46027. }
  46028. else {
  46029. //2016-03-08 this part is for managing backward compatibility
  46030. for (var n in this.attached) {
  46031. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46032. if (construct) {
  46033. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46034. this.remove(this.attached[n]);
  46035. this.add(input);
  46036. }
  46037. }
  46038. }
  46039. };
  46040. return CameraInputsManager;
  46041. }());
  46042. BABYLON.CameraInputsManager = CameraInputsManager;
  46043. })(BABYLON || (BABYLON = {}));
  46044. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46045. var BABYLON;
  46046. (function (BABYLON) {
  46047. var TargetCamera = /** @class */ (function (_super) {
  46048. __extends(TargetCamera, _super);
  46049. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46050. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46051. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46052. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46053. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46054. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46055. _this.speed = 2.0;
  46056. _this.noRotationConstraint = false;
  46057. _this.lockedTarget = null;
  46058. _this._currentTarget = BABYLON.Vector3.Zero();
  46059. _this._viewMatrix = BABYLON.Matrix.Zero();
  46060. _this._camMatrix = BABYLON.Matrix.Zero();
  46061. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46062. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46063. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46064. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46065. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46066. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46067. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46068. return _this;
  46069. }
  46070. TargetCamera.prototype.getFrontPosition = function (distance) {
  46071. this.getWorldMatrix();
  46072. var direction = this.getTarget().subtract(this.position);
  46073. direction.normalize();
  46074. direction.scaleInPlace(distance);
  46075. return this.globalPosition.add(direction);
  46076. };
  46077. TargetCamera.prototype._getLockedTargetPosition = function () {
  46078. if (!this.lockedTarget) {
  46079. return null;
  46080. }
  46081. if (this.lockedTarget.absolutePosition) {
  46082. this.lockedTarget.computeWorldMatrix();
  46083. }
  46084. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46085. };
  46086. TargetCamera.prototype.storeState = function () {
  46087. this._storedPosition = this.position.clone();
  46088. this._storedRotation = this.rotation.clone();
  46089. if (this.rotationQuaternion) {
  46090. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46091. }
  46092. return _super.prototype.storeState.call(this);
  46093. };
  46094. /**
  46095. * Restored camera state. You must call storeState() first
  46096. */
  46097. TargetCamera.prototype._restoreStateValues = function () {
  46098. if (!_super.prototype._restoreStateValues.call(this)) {
  46099. return false;
  46100. }
  46101. this.position = this._storedPosition.clone();
  46102. this.rotation = this._storedRotation.clone();
  46103. if (this.rotationQuaternion) {
  46104. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46105. }
  46106. this.cameraDirection.copyFromFloats(0, 0, 0);
  46107. this.cameraRotation.copyFromFloats(0, 0);
  46108. return true;
  46109. };
  46110. // Cache
  46111. TargetCamera.prototype._initCache = function () {
  46112. _super.prototype._initCache.call(this);
  46113. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46114. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46115. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46116. };
  46117. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46118. if (!ignoreParentClass) {
  46119. _super.prototype._updateCache.call(this);
  46120. }
  46121. var lockedTargetPosition = this._getLockedTargetPosition();
  46122. if (!lockedTargetPosition) {
  46123. this._cache.lockedTarget = null;
  46124. }
  46125. else {
  46126. if (!this._cache.lockedTarget) {
  46127. this._cache.lockedTarget = lockedTargetPosition.clone();
  46128. }
  46129. else {
  46130. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46131. }
  46132. }
  46133. this._cache.rotation.copyFrom(this.rotation);
  46134. if (this.rotationQuaternion)
  46135. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46136. };
  46137. // Synchronized
  46138. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46139. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46140. return false;
  46141. }
  46142. var lockedTargetPosition = this._getLockedTargetPosition();
  46143. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46144. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46145. };
  46146. // Methods
  46147. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46148. var engine = this.getEngine();
  46149. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46150. };
  46151. // Target
  46152. TargetCamera.prototype.setTarget = function (target) {
  46153. this.upVector.normalize();
  46154. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46155. this._camMatrix.invert();
  46156. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46157. var vDir = target.subtract(this.position);
  46158. if (vDir.x >= 0.0) {
  46159. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46160. }
  46161. else {
  46162. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46163. }
  46164. this.rotation.z = 0;
  46165. if (isNaN(this.rotation.x)) {
  46166. this.rotation.x = 0;
  46167. }
  46168. if (isNaN(this.rotation.y)) {
  46169. this.rotation.y = 0;
  46170. }
  46171. if (isNaN(this.rotation.z)) {
  46172. this.rotation.z = 0;
  46173. }
  46174. if (this.rotationQuaternion) {
  46175. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46176. }
  46177. };
  46178. /**
  46179. * Return the current target position of the camera. This value is expressed in local space.
  46180. */
  46181. TargetCamera.prototype.getTarget = function () {
  46182. return this._currentTarget;
  46183. };
  46184. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46185. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46186. };
  46187. TargetCamera.prototype._updatePosition = function () {
  46188. if (this.parent) {
  46189. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46190. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46191. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46192. return;
  46193. }
  46194. this.position.addInPlace(this.cameraDirection);
  46195. };
  46196. TargetCamera.prototype._checkInputs = function () {
  46197. var needToMove = this._decideIfNeedsToMove();
  46198. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46199. // Move
  46200. if (needToMove) {
  46201. this._updatePosition();
  46202. }
  46203. // Rotate
  46204. if (needToRotate) {
  46205. this.rotation.x += this.cameraRotation.x;
  46206. this.rotation.y += this.cameraRotation.y;
  46207. //rotate, if quaternion is set and rotation was used
  46208. if (this.rotationQuaternion) {
  46209. var len = this.rotation.lengthSquared();
  46210. if (len) {
  46211. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46212. }
  46213. }
  46214. if (!this.noRotationConstraint) {
  46215. var limit = (Math.PI / 2) * 0.95;
  46216. if (this.rotation.x > limit)
  46217. this.rotation.x = limit;
  46218. if (this.rotation.x < -limit)
  46219. this.rotation.x = -limit;
  46220. }
  46221. }
  46222. // Inertia
  46223. if (needToMove) {
  46224. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46225. this.cameraDirection.x = 0;
  46226. }
  46227. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46228. this.cameraDirection.y = 0;
  46229. }
  46230. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46231. this.cameraDirection.z = 0;
  46232. }
  46233. this.cameraDirection.scaleInPlace(this.inertia);
  46234. }
  46235. if (needToRotate) {
  46236. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46237. this.cameraRotation.x = 0;
  46238. }
  46239. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46240. this.cameraRotation.y = 0;
  46241. }
  46242. this.cameraRotation.scaleInPlace(this.inertia);
  46243. }
  46244. _super.prototype._checkInputs.call(this);
  46245. };
  46246. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46247. if (this.rotationQuaternion) {
  46248. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46249. }
  46250. else {
  46251. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46252. }
  46253. //update the up vector!
  46254. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46255. };
  46256. TargetCamera.prototype._getViewMatrix = function () {
  46257. if (this.lockedTarget) {
  46258. this.setTarget(this._getLockedTargetPosition());
  46259. }
  46260. // Compute
  46261. this._updateCameraRotationMatrix();
  46262. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46263. // Computing target and final matrix
  46264. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46265. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46266. return this._viewMatrix;
  46267. };
  46268. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46269. if (this.parent) {
  46270. var parentWorldMatrix = this.parent.getWorldMatrix();
  46271. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46272. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46273. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46274. this._markSyncedWithParent();
  46275. }
  46276. else {
  46277. this._globalPosition.copyFrom(this.position);
  46278. this._globalCurrentTarget.copyFrom(target);
  46279. this._globalCurrentUpVector.copyFrom(up);
  46280. }
  46281. if (this.getScene().useRightHandedSystem) {
  46282. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46283. }
  46284. else {
  46285. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46286. }
  46287. };
  46288. /**
  46289. * @override
  46290. * Override Camera.createRigCamera
  46291. */
  46292. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46293. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46294. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46295. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46296. if (!this.rotationQuaternion) {
  46297. this.rotationQuaternion = new BABYLON.Quaternion();
  46298. }
  46299. rigCamera._cameraRigParams = {};
  46300. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46301. }
  46302. return rigCamera;
  46303. }
  46304. return null;
  46305. };
  46306. /**
  46307. * @override
  46308. * Override Camera._updateRigCameras
  46309. */
  46310. TargetCamera.prototype._updateRigCameras = function () {
  46311. var camLeft = this._rigCameras[0];
  46312. var camRight = this._rigCameras[1];
  46313. switch (this.cameraRigMode) {
  46314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46315. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46316. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46317. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46318. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46319. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46320. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46321. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46322. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46323. camLeft.setTarget(this.getTarget());
  46324. camRight.setTarget(this.getTarget());
  46325. break;
  46326. case BABYLON.Camera.RIG_MODE_VR:
  46327. if (camLeft.rotationQuaternion) {
  46328. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46329. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46330. }
  46331. else {
  46332. camLeft.rotation.copyFrom(this.rotation);
  46333. camRight.rotation.copyFrom(this.rotation);
  46334. }
  46335. camLeft.position.copyFrom(this.position);
  46336. camRight.position.copyFrom(this.position);
  46337. break;
  46338. }
  46339. _super.prototype._updateRigCameras.call(this);
  46340. };
  46341. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46342. if (!this._rigCamTransformMatrix) {
  46343. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46344. }
  46345. var target = this.getTarget();
  46346. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46347. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46348. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46349. };
  46350. TargetCamera.prototype.getClassName = function () {
  46351. return "TargetCamera";
  46352. };
  46353. __decorate([
  46354. BABYLON.serializeAsVector3()
  46355. ], TargetCamera.prototype, "rotation", void 0);
  46356. __decorate([
  46357. BABYLON.serialize()
  46358. ], TargetCamera.prototype, "speed", void 0);
  46359. __decorate([
  46360. BABYLON.serializeAsMeshReference("lockedTargetId")
  46361. ], TargetCamera.prototype, "lockedTarget", void 0);
  46362. return TargetCamera;
  46363. }(BABYLON.Camera));
  46364. BABYLON.TargetCamera = TargetCamera;
  46365. })(BABYLON || (BABYLON = {}));
  46366. //# sourceMappingURL=babylon.targetCamera.js.map
  46367. var BABYLON;
  46368. (function (BABYLON) {
  46369. var FreeCameraMouseInput = /** @class */ (function () {
  46370. function FreeCameraMouseInput(touchEnabled) {
  46371. if (touchEnabled === void 0) { touchEnabled = true; }
  46372. this.touchEnabled = touchEnabled;
  46373. this.buttons = [0, 1, 2];
  46374. this.angularSensibility = 2000.0;
  46375. this.previousPosition = null;
  46376. }
  46377. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46378. var _this = this;
  46379. var engine = this.camera.getEngine();
  46380. if (!this._pointerInput) {
  46381. this._pointerInput = function (p, s) {
  46382. var evt = p.event;
  46383. if (engine.isInVRExclusivePointerMode) {
  46384. return;
  46385. }
  46386. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46387. return;
  46388. }
  46389. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46390. return;
  46391. }
  46392. var srcElement = (evt.srcElement || evt.target);
  46393. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46394. try {
  46395. srcElement.setPointerCapture(evt.pointerId);
  46396. }
  46397. catch (e) {
  46398. //Nothing to do with the error. Execution will continue.
  46399. }
  46400. _this.previousPosition = {
  46401. x: evt.clientX,
  46402. y: evt.clientY
  46403. };
  46404. if (!noPreventDefault) {
  46405. evt.preventDefault();
  46406. element.focus();
  46407. }
  46408. }
  46409. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46410. try {
  46411. srcElement.releasePointerCapture(evt.pointerId);
  46412. }
  46413. catch (e) {
  46414. //Nothing to do with the error.
  46415. }
  46416. _this.previousPosition = null;
  46417. if (!noPreventDefault) {
  46418. evt.preventDefault();
  46419. }
  46420. }
  46421. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46422. if (!_this.previousPosition || engine.isPointerLock) {
  46423. return;
  46424. }
  46425. var offsetX = evt.clientX - _this.previousPosition.x;
  46426. if (_this.camera.getScene().useRightHandedSystem)
  46427. offsetX *= -1;
  46428. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46429. offsetX *= -1;
  46430. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46431. var offsetY = evt.clientY - _this.previousPosition.y;
  46432. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46433. _this.previousPosition = {
  46434. x: evt.clientX,
  46435. y: evt.clientY
  46436. };
  46437. if (!noPreventDefault) {
  46438. evt.preventDefault();
  46439. }
  46440. }
  46441. };
  46442. }
  46443. this._onMouseMove = function (evt) {
  46444. if (!engine.isPointerLock) {
  46445. return;
  46446. }
  46447. if (engine.isInVRExclusivePointerMode) {
  46448. return;
  46449. }
  46450. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46451. if (_this.camera.getScene().useRightHandedSystem)
  46452. offsetX *= -1;
  46453. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46454. offsetX *= -1;
  46455. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46456. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46457. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46458. _this.previousPosition = null;
  46459. if (!noPreventDefault) {
  46460. evt.preventDefault();
  46461. }
  46462. };
  46463. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46464. element.addEventListener("mousemove", this._onMouseMove, false);
  46465. };
  46466. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46467. if (this._observer && element) {
  46468. this.camera.getScene().onPointerObservable.remove(this._observer);
  46469. if (this._onMouseMove) {
  46470. element.removeEventListener("mousemove", this._onMouseMove);
  46471. }
  46472. this._observer = null;
  46473. this._onMouseMove = null;
  46474. this.previousPosition = null;
  46475. }
  46476. };
  46477. FreeCameraMouseInput.prototype.getClassName = function () {
  46478. return "FreeCameraMouseInput";
  46479. };
  46480. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46481. return "mouse";
  46482. };
  46483. __decorate([
  46484. BABYLON.serialize()
  46485. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46486. __decorate([
  46487. BABYLON.serialize()
  46488. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46489. return FreeCameraMouseInput;
  46490. }());
  46491. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46492. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46493. })(BABYLON || (BABYLON = {}));
  46494. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46495. var BABYLON;
  46496. (function (BABYLON) {
  46497. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46498. function FreeCameraKeyboardMoveInput() {
  46499. this._keys = new Array();
  46500. this.keysUp = [38];
  46501. this.keysDown = [40];
  46502. this.keysLeft = [37];
  46503. this.keysRight = [39];
  46504. }
  46505. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46506. var _this = this;
  46507. if (this._onCanvasBlurObserver) {
  46508. return;
  46509. }
  46510. this._scene = this.camera.getScene();
  46511. this._engine = this._scene.getEngine();
  46512. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46513. _this._keys = [];
  46514. });
  46515. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46516. var evt = info.event;
  46517. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46518. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46519. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46520. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46521. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46522. var index = _this._keys.indexOf(evt.keyCode);
  46523. if (index === -1) {
  46524. _this._keys.push(evt.keyCode);
  46525. }
  46526. if (!noPreventDefault) {
  46527. evt.preventDefault();
  46528. }
  46529. }
  46530. }
  46531. else {
  46532. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46533. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46534. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46535. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46536. var index = _this._keys.indexOf(evt.keyCode);
  46537. if (index >= 0) {
  46538. _this._keys.splice(index, 1);
  46539. }
  46540. if (!noPreventDefault) {
  46541. evt.preventDefault();
  46542. }
  46543. }
  46544. }
  46545. });
  46546. };
  46547. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46548. if (this._scene) {
  46549. if (this._onKeyboardObserver) {
  46550. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46551. }
  46552. if (this._onCanvasBlurObserver) {
  46553. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46554. }
  46555. this._onKeyboardObserver = null;
  46556. this._onCanvasBlurObserver = null;
  46557. }
  46558. this._keys = [];
  46559. };
  46560. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46561. if (this._onKeyboardObserver) {
  46562. var camera = this.camera;
  46563. // Keyboard
  46564. for (var index = 0; index < this._keys.length; index++) {
  46565. var keyCode = this._keys[index];
  46566. var speed = camera._computeLocalCameraSpeed();
  46567. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46568. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46569. }
  46570. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46571. camera._localDirection.copyFromFloats(0, 0, speed);
  46572. }
  46573. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46574. camera._localDirection.copyFromFloats(speed, 0, 0);
  46575. }
  46576. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46577. camera._localDirection.copyFromFloats(0, 0, -speed);
  46578. }
  46579. if (camera.getScene().useRightHandedSystem) {
  46580. camera._localDirection.z *= -1;
  46581. }
  46582. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46583. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46584. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46585. }
  46586. }
  46587. };
  46588. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46589. return "FreeCameraKeyboardMoveInput";
  46590. };
  46591. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46592. this._keys = [];
  46593. };
  46594. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46595. return "keyboard";
  46596. };
  46597. __decorate([
  46598. BABYLON.serialize()
  46599. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46600. __decorate([
  46601. BABYLON.serialize()
  46602. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46603. __decorate([
  46604. BABYLON.serialize()
  46605. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46606. __decorate([
  46607. BABYLON.serialize()
  46608. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46609. return FreeCameraKeyboardMoveInput;
  46610. }());
  46611. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46612. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46613. })(BABYLON || (BABYLON = {}));
  46614. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46615. var BABYLON;
  46616. (function (BABYLON) {
  46617. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46618. __extends(FreeCameraInputsManager, _super);
  46619. function FreeCameraInputsManager(camera) {
  46620. return _super.call(this, camera) || this;
  46621. }
  46622. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46623. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46624. return this;
  46625. };
  46626. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46627. if (touchEnabled === void 0) { touchEnabled = true; }
  46628. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46629. return this;
  46630. };
  46631. FreeCameraInputsManager.prototype.addGamepad = function () {
  46632. this.add(new BABYLON.FreeCameraGamepadInput());
  46633. return this;
  46634. };
  46635. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46636. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46637. return this;
  46638. };
  46639. FreeCameraInputsManager.prototype.addTouch = function () {
  46640. this.add(new BABYLON.FreeCameraTouchInput());
  46641. return this;
  46642. };
  46643. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46644. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46645. return this;
  46646. };
  46647. return FreeCameraInputsManager;
  46648. }(BABYLON.CameraInputsManager));
  46649. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46650. })(BABYLON || (BABYLON = {}));
  46651. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46652. var BABYLON;
  46653. (function (BABYLON) {
  46654. var FreeCamera = /** @class */ (function (_super) {
  46655. __extends(FreeCamera, _super);
  46656. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46657. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46658. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46659. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46660. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46661. _this.checkCollisions = false;
  46662. _this.applyGravity = false;
  46663. _this._needMoveForGravity = false;
  46664. _this._oldPosition = BABYLON.Vector3.Zero();
  46665. _this._diffPosition = BABYLON.Vector3.Zero();
  46666. _this._newPosition = BABYLON.Vector3.Zero();
  46667. // Collisions
  46668. _this._collisionMask = -1;
  46669. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46670. if (collidedMesh === void 0) { collidedMesh = null; }
  46671. //TODO move this to the collision coordinator!
  46672. if (_this.getScene().workerCollisions)
  46673. newPosition.multiplyInPlace(_this._collider._radius);
  46674. var updatePosition = function (newPos) {
  46675. _this._newPosition.copyFrom(newPos);
  46676. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46677. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46678. _this.position.addInPlace(_this._diffPosition);
  46679. if (_this.onCollide && collidedMesh) {
  46680. _this.onCollide(collidedMesh);
  46681. }
  46682. }
  46683. };
  46684. updatePosition(newPosition);
  46685. };
  46686. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46687. _this.inputs.addKeyboard().addMouse();
  46688. return _this;
  46689. }
  46690. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46691. //-- begin properties for backward compatibility for inputs
  46692. /**
  46693. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46694. * Higher values reduce sensitivity.
  46695. */
  46696. get: function () {
  46697. var mouse = this.inputs.attached["mouse"];
  46698. if (mouse)
  46699. return mouse.angularSensibility;
  46700. return 0;
  46701. },
  46702. /**
  46703. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46704. * Higher values reduce sensitivity.
  46705. */
  46706. set: function (value) {
  46707. var mouse = this.inputs.attached["mouse"];
  46708. if (mouse)
  46709. mouse.angularSensibility = value;
  46710. },
  46711. enumerable: true,
  46712. configurable: true
  46713. });
  46714. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46715. get: function () {
  46716. var keyboard = this.inputs.attached["keyboard"];
  46717. if (keyboard)
  46718. return keyboard.keysUp;
  46719. return [];
  46720. },
  46721. set: function (value) {
  46722. var keyboard = this.inputs.attached["keyboard"];
  46723. if (keyboard)
  46724. keyboard.keysUp = value;
  46725. },
  46726. enumerable: true,
  46727. configurable: true
  46728. });
  46729. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46730. get: function () {
  46731. var keyboard = this.inputs.attached["keyboard"];
  46732. if (keyboard)
  46733. return keyboard.keysDown;
  46734. return [];
  46735. },
  46736. set: function (value) {
  46737. var keyboard = this.inputs.attached["keyboard"];
  46738. if (keyboard)
  46739. keyboard.keysDown = value;
  46740. },
  46741. enumerable: true,
  46742. configurable: true
  46743. });
  46744. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46745. get: function () {
  46746. var keyboard = this.inputs.attached["keyboard"];
  46747. if (keyboard)
  46748. return keyboard.keysLeft;
  46749. return [];
  46750. },
  46751. set: function (value) {
  46752. var keyboard = this.inputs.attached["keyboard"];
  46753. if (keyboard)
  46754. keyboard.keysLeft = value;
  46755. },
  46756. enumerable: true,
  46757. configurable: true
  46758. });
  46759. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46760. get: function () {
  46761. var keyboard = this.inputs.attached["keyboard"];
  46762. if (keyboard)
  46763. return keyboard.keysRight;
  46764. return [];
  46765. },
  46766. set: function (value) {
  46767. var keyboard = this.inputs.attached["keyboard"];
  46768. if (keyboard)
  46769. keyboard.keysRight = value;
  46770. },
  46771. enumerable: true,
  46772. configurable: true
  46773. });
  46774. // Controls
  46775. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46776. this.inputs.attachElement(element, noPreventDefault);
  46777. };
  46778. FreeCamera.prototype.detachControl = function (element) {
  46779. this.inputs.detachElement(element);
  46780. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46781. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46782. };
  46783. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46784. get: function () {
  46785. return this._collisionMask;
  46786. },
  46787. set: function (mask) {
  46788. this._collisionMask = !isNaN(mask) ? mask : -1;
  46789. },
  46790. enumerable: true,
  46791. configurable: true
  46792. });
  46793. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46794. var globalPosition;
  46795. if (this.parent) {
  46796. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46797. }
  46798. else {
  46799. globalPosition = this.position;
  46800. }
  46801. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46802. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46803. if (!this._collider) {
  46804. this._collider = new BABYLON.Collider();
  46805. }
  46806. this._collider._radius = this.ellipsoid;
  46807. this._collider.collisionMask = this._collisionMask;
  46808. //no need for clone, as long as gravity is not on.
  46809. var actualDisplacement = displacement;
  46810. //add gravity to the direction to prevent the dual-collision checking
  46811. if (this.applyGravity) {
  46812. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46813. actualDisplacement = displacement.add(this.getScene().gravity);
  46814. }
  46815. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46816. };
  46817. FreeCamera.prototype._checkInputs = function () {
  46818. if (!this._localDirection) {
  46819. this._localDirection = BABYLON.Vector3.Zero();
  46820. this._transformedDirection = BABYLON.Vector3.Zero();
  46821. }
  46822. this.inputs.checkInputs();
  46823. _super.prototype._checkInputs.call(this);
  46824. };
  46825. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46826. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46827. };
  46828. FreeCamera.prototype._updatePosition = function () {
  46829. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46830. this._collideWithWorld(this.cameraDirection);
  46831. }
  46832. else {
  46833. _super.prototype._updatePosition.call(this);
  46834. }
  46835. };
  46836. FreeCamera.prototype.dispose = function () {
  46837. this.inputs.clear();
  46838. _super.prototype.dispose.call(this);
  46839. };
  46840. FreeCamera.prototype.getClassName = function () {
  46841. return "FreeCamera";
  46842. };
  46843. __decorate([
  46844. BABYLON.serializeAsVector3()
  46845. ], FreeCamera.prototype, "ellipsoid", void 0);
  46846. __decorate([
  46847. BABYLON.serializeAsVector3()
  46848. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46849. __decorate([
  46850. BABYLON.serialize()
  46851. ], FreeCamera.prototype, "checkCollisions", void 0);
  46852. __decorate([
  46853. BABYLON.serialize()
  46854. ], FreeCamera.prototype, "applyGravity", void 0);
  46855. return FreeCamera;
  46856. }(BABYLON.TargetCamera));
  46857. BABYLON.FreeCamera = FreeCamera;
  46858. })(BABYLON || (BABYLON = {}));
  46859. //# sourceMappingURL=babylon.freeCamera.js.map
  46860. var BABYLON;
  46861. (function (BABYLON) {
  46862. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46863. function ArcRotateCameraKeyboardMoveInput() {
  46864. this._keys = new Array();
  46865. this.keysUp = [38];
  46866. this.keysDown = [40];
  46867. this.keysLeft = [37];
  46868. this.keysRight = [39];
  46869. this.keysReset = [220];
  46870. this.panningSensibility = 50.0;
  46871. this.zoomingSensibility = 25.0;
  46872. this.useAltToZoom = true;
  46873. }
  46874. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46875. var _this = this;
  46876. if (this._onCanvasBlurObserver) {
  46877. return;
  46878. }
  46879. this._scene = this.camera.getScene();
  46880. this._engine = this._scene.getEngine();
  46881. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46882. _this._keys = [];
  46883. });
  46884. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46885. var evt = info.event;
  46886. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46887. _this._ctrlPressed = evt.ctrlKey;
  46888. _this._altPressed = evt.altKey;
  46889. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46890. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46891. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46892. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46893. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46894. var index = _this._keys.indexOf(evt.keyCode);
  46895. if (index === -1) {
  46896. _this._keys.push(evt.keyCode);
  46897. }
  46898. if (evt.preventDefault) {
  46899. if (!noPreventDefault) {
  46900. evt.preventDefault();
  46901. }
  46902. }
  46903. }
  46904. }
  46905. else {
  46906. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46907. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46908. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46909. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46910. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46911. var index = _this._keys.indexOf(evt.keyCode);
  46912. if (index >= 0) {
  46913. _this._keys.splice(index, 1);
  46914. }
  46915. if (evt.preventDefault) {
  46916. if (!noPreventDefault) {
  46917. evt.preventDefault();
  46918. }
  46919. }
  46920. }
  46921. }
  46922. });
  46923. };
  46924. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46925. if (this._scene) {
  46926. if (this._onKeyboardObserver) {
  46927. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46928. }
  46929. if (this._onCanvasBlurObserver) {
  46930. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46931. }
  46932. this._onKeyboardObserver = null;
  46933. this._onCanvasBlurObserver = null;
  46934. }
  46935. this._keys = [];
  46936. };
  46937. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46938. if (this._onKeyboardObserver) {
  46939. var camera = this.camera;
  46940. for (var index = 0; index < this._keys.length; index++) {
  46941. var keyCode = this._keys[index];
  46942. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46943. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46944. camera.inertialPanningX -= 1 / this.panningSensibility;
  46945. }
  46946. else {
  46947. camera.inertialAlphaOffset -= 0.01;
  46948. }
  46949. }
  46950. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46951. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46952. camera.inertialPanningY += 1 / this.panningSensibility;
  46953. }
  46954. else if (this._altPressed && this.useAltToZoom) {
  46955. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  46956. }
  46957. else {
  46958. camera.inertialBetaOffset -= 0.01;
  46959. }
  46960. }
  46961. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46962. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46963. camera.inertialPanningX += 1 / this.panningSensibility;
  46964. }
  46965. else {
  46966. camera.inertialAlphaOffset += 0.01;
  46967. }
  46968. }
  46969. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46970. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  46971. camera.inertialPanningY -= 1 / this.panningSensibility;
  46972. }
  46973. else if (this._altPressed && this.useAltToZoom) {
  46974. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  46975. }
  46976. else {
  46977. camera.inertialBetaOffset += 0.01;
  46978. }
  46979. }
  46980. else if (this.keysReset.indexOf(keyCode) !== -1) {
  46981. camera.restoreState();
  46982. }
  46983. }
  46984. }
  46985. };
  46986. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  46987. return "ArcRotateCameraKeyboardMoveInput";
  46988. };
  46989. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46990. return "keyboard";
  46991. };
  46992. __decorate([
  46993. BABYLON.serialize()
  46994. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46995. __decorate([
  46996. BABYLON.serialize()
  46997. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46998. __decorate([
  46999. BABYLON.serialize()
  47000. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47001. __decorate([
  47002. BABYLON.serialize()
  47003. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47004. __decorate([
  47005. BABYLON.serialize()
  47006. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47007. __decorate([
  47008. BABYLON.serialize()
  47009. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47010. __decorate([
  47011. BABYLON.serialize()
  47012. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47013. __decorate([
  47014. BABYLON.serialize()
  47015. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47016. return ArcRotateCameraKeyboardMoveInput;
  47017. }());
  47018. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47019. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47020. })(BABYLON || (BABYLON = {}));
  47021. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47022. var BABYLON;
  47023. (function (BABYLON) {
  47024. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47025. function ArcRotateCameraMouseWheelInput() {
  47026. this.wheelPrecision = 3.0;
  47027. /**
  47028. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47029. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47030. */
  47031. this.wheelDeltaPercentage = 0;
  47032. }
  47033. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47034. var _this = this;
  47035. this._wheel = function (p, s) {
  47036. //sanity check - this should be a PointerWheel event.
  47037. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47038. return;
  47039. var event = p.event;
  47040. var delta = 0;
  47041. if (event.wheelDelta) {
  47042. if (_this.wheelDeltaPercentage) {
  47043. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47044. if (event.wheelDelta > 0) {
  47045. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47046. }
  47047. else {
  47048. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47049. }
  47050. }
  47051. else {
  47052. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47053. }
  47054. }
  47055. else if (event.detail) {
  47056. delta = -event.detail / _this.wheelPrecision;
  47057. }
  47058. if (delta)
  47059. _this.camera.inertialRadiusOffset += delta;
  47060. if (event.preventDefault) {
  47061. if (!noPreventDefault) {
  47062. event.preventDefault();
  47063. }
  47064. }
  47065. };
  47066. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47067. };
  47068. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47069. if (this._observer && element) {
  47070. this.camera.getScene().onPointerObservable.remove(this._observer);
  47071. this._observer = null;
  47072. this._wheel = null;
  47073. }
  47074. };
  47075. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47076. return "ArcRotateCameraMouseWheelInput";
  47077. };
  47078. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47079. return "mousewheel";
  47080. };
  47081. __decorate([
  47082. BABYLON.serialize()
  47083. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47084. __decorate([
  47085. BABYLON.serialize()
  47086. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47087. return ArcRotateCameraMouseWheelInput;
  47088. }());
  47089. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47090. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47091. })(BABYLON || (BABYLON = {}));
  47092. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47093. var BABYLON;
  47094. (function (BABYLON) {
  47095. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47096. function ArcRotateCameraPointersInput() {
  47097. this.buttons = [0, 1, 2];
  47098. this.angularSensibilityX = 1000.0;
  47099. this.angularSensibilityY = 1000.0;
  47100. this.pinchPrecision = 12.0;
  47101. /**
  47102. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47103. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47104. */
  47105. this.pinchDeltaPercentage = 0;
  47106. this.panningSensibility = 1000.0;
  47107. this.multiTouchPanning = true;
  47108. this.multiTouchPanAndZoom = true;
  47109. this._isPanClick = false;
  47110. this.pinchInwards = true;
  47111. }
  47112. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47113. var _this = this;
  47114. var engine = this.camera.getEngine();
  47115. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47116. var pointA = null;
  47117. var pointB = null;
  47118. var previousPinchSquaredDistance = 0;
  47119. var initialDistance = 0;
  47120. var twoFingerActivityCount = 0;
  47121. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47122. this._pointerInput = function (p, s) {
  47123. var evt = p.event;
  47124. var isTouch = p.event.pointerType === "touch";
  47125. if (engine.isInVRExclusivePointerMode) {
  47126. return;
  47127. }
  47128. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47129. return;
  47130. }
  47131. var srcElement = (evt.srcElement || evt.target);
  47132. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47133. try {
  47134. srcElement.setPointerCapture(evt.pointerId);
  47135. }
  47136. catch (e) {
  47137. //Nothing to do with the error. Execution will continue.
  47138. }
  47139. // Manage panning with pan button click
  47140. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47141. // manage pointers
  47142. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47143. if (pointA === null) {
  47144. pointA = cacheSoloPointer;
  47145. }
  47146. else if (pointB === null) {
  47147. pointB = cacheSoloPointer;
  47148. }
  47149. if (!noPreventDefault) {
  47150. evt.preventDefault();
  47151. element.focus();
  47152. }
  47153. }
  47154. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47155. _this.camera.restoreState();
  47156. }
  47157. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47158. try {
  47159. srcElement.releasePointerCapture(evt.pointerId);
  47160. }
  47161. catch (e) {
  47162. //Nothing to do with the error.
  47163. }
  47164. cacheSoloPointer = null;
  47165. previousPinchSquaredDistance = 0;
  47166. previousMultiTouchPanPosition.isPaning = false;
  47167. previousMultiTouchPanPosition.isPinching = false;
  47168. twoFingerActivityCount = 0;
  47169. initialDistance = 0;
  47170. if (!isTouch) {
  47171. pointB = null; // Mouse and pen are mono pointer
  47172. }
  47173. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47174. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47175. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47176. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47177. if (engine._badOS) {
  47178. pointA = pointB = null;
  47179. }
  47180. else {
  47181. //only remove the impacted pointer in case of multitouch allowing on most
  47182. //platforms switching from rotate to zoom and pan seamlessly.
  47183. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47184. pointA = pointB;
  47185. pointB = null;
  47186. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47187. }
  47188. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47189. pointB = null;
  47190. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47191. }
  47192. else {
  47193. pointA = pointB = null;
  47194. }
  47195. }
  47196. if (!noPreventDefault) {
  47197. evt.preventDefault();
  47198. }
  47199. }
  47200. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47201. if (!noPreventDefault) {
  47202. evt.preventDefault();
  47203. }
  47204. // One button down
  47205. if (pointA && pointB === null && cacheSoloPointer) {
  47206. if (_this.panningSensibility !== 0 &&
  47207. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47208. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47209. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47210. }
  47211. else {
  47212. var offsetX = evt.clientX - cacheSoloPointer.x;
  47213. var offsetY = evt.clientY - cacheSoloPointer.y;
  47214. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47215. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47216. }
  47217. cacheSoloPointer.x = evt.clientX;
  47218. cacheSoloPointer.y = evt.clientY;
  47219. }
  47220. // Two buttons down: pinch/pan
  47221. else if (pointA && pointB) {
  47222. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47223. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47224. ed.x = evt.clientX;
  47225. ed.y = evt.clientY;
  47226. var direction = _this.pinchInwards ? 1 : -1;
  47227. var distX = pointA.x - pointB.x;
  47228. var distY = pointA.y - pointB.y;
  47229. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47230. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47231. if (previousPinchSquaredDistance === 0) {
  47232. initialDistance = pinchDistance;
  47233. previousPinchSquaredDistance = pinchSquaredDistance;
  47234. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47235. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47236. return;
  47237. }
  47238. if (_this.multiTouchPanAndZoom) {
  47239. if (_this.pinchDeltaPercentage) {
  47240. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47241. }
  47242. else {
  47243. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47244. (_this.pinchPrecision *
  47245. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47246. direction);
  47247. }
  47248. if (_this.panningSensibility !== 0) {
  47249. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47250. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47251. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47252. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47253. previousMultiTouchPanPosition.x = pointersCenterX;
  47254. previousMultiTouchPanPosition.y = pointersCenterY;
  47255. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47256. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47257. }
  47258. }
  47259. else {
  47260. twoFingerActivityCount++;
  47261. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47262. if (_this.pinchDeltaPercentage) {
  47263. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47264. }
  47265. else {
  47266. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47267. (_this.pinchPrecision *
  47268. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47269. direction);
  47270. }
  47271. previousMultiTouchPanPosition.isPaning = false;
  47272. previousMultiTouchPanPosition.isPinching = true;
  47273. }
  47274. else {
  47275. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47276. if (!previousMultiTouchPanPosition.isPaning) {
  47277. previousMultiTouchPanPosition.isPaning = true;
  47278. previousMultiTouchPanPosition.isPinching = false;
  47279. previousMultiTouchPanPosition.x = ed.x;
  47280. previousMultiTouchPanPosition.y = ed.y;
  47281. return;
  47282. }
  47283. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47284. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47285. }
  47286. }
  47287. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47288. previousMultiTouchPanPosition.x = ed.x;
  47289. previousMultiTouchPanPosition.y = ed.y;
  47290. }
  47291. }
  47292. previousPinchSquaredDistance = pinchSquaredDistance;
  47293. }
  47294. }
  47295. };
  47296. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47297. this._onContextMenu = function (evt) {
  47298. evt.preventDefault();
  47299. };
  47300. if (!this.camera._useCtrlForPanning) {
  47301. element.addEventListener("contextmenu", this._onContextMenu, false);
  47302. }
  47303. this._onLostFocus = function () {
  47304. //this._keys = [];
  47305. pointA = pointB = null;
  47306. previousPinchSquaredDistance = 0;
  47307. previousMultiTouchPanPosition.isPaning = false;
  47308. previousMultiTouchPanPosition.isPinching = false;
  47309. twoFingerActivityCount = 0;
  47310. cacheSoloPointer = null;
  47311. initialDistance = 0;
  47312. };
  47313. this._onMouseMove = function (evt) {
  47314. if (!engine.isPointerLock) {
  47315. return;
  47316. }
  47317. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47318. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47319. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47320. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47321. if (!noPreventDefault) {
  47322. evt.preventDefault();
  47323. }
  47324. };
  47325. this._onGestureStart = function (e) {
  47326. if (window.MSGesture === undefined) {
  47327. return;
  47328. }
  47329. if (!_this._MSGestureHandler) {
  47330. _this._MSGestureHandler = new MSGesture();
  47331. _this._MSGestureHandler.target = element;
  47332. }
  47333. _this._MSGestureHandler.addPointer(e.pointerId);
  47334. };
  47335. this._onGesture = function (e) {
  47336. _this.camera.radius *= e.scale;
  47337. if (e.preventDefault) {
  47338. if (!noPreventDefault) {
  47339. e.stopPropagation();
  47340. e.preventDefault();
  47341. }
  47342. }
  47343. };
  47344. element.addEventListener("mousemove", this._onMouseMove, false);
  47345. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47346. element.addEventListener("MSGestureChange", this._onGesture, false);
  47347. BABYLON.Tools.RegisterTopRootEvents([
  47348. { name: "blur", handler: this._onLostFocus }
  47349. ]);
  47350. };
  47351. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47352. if (this._onLostFocus) {
  47353. BABYLON.Tools.UnregisterTopRootEvents([
  47354. { name: "blur", handler: this._onLostFocus }
  47355. ]);
  47356. }
  47357. if (element && this._observer) {
  47358. this.camera.getScene().onPointerObservable.remove(this._observer);
  47359. this._observer = null;
  47360. if (this._onContextMenu) {
  47361. element.removeEventListener("contextmenu", this._onContextMenu);
  47362. }
  47363. if (this._onMouseMove) {
  47364. element.removeEventListener("mousemove", this._onMouseMove);
  47365. }
  47366. if (this._onGestureStart) {
  47367. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47368. }
  47369. if (this._onGesture) {
  47370. element.removeEventListener("MSGestureChange", this._onGesture);
  47371. }
  47372. this._isPanClick = false;
  47373. this.pinchInwards = true;
  47374. this._onMouseMove = null;
  47375. this._onGestureStart = null;
  47376. this._onGesture = null;
  47377. this._MSGestureHandler = null;
  47378. this._onLostFocus = null;
  47379. this._onContextMenu = null;
  47380. }
  47381. };
  47382. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47383. return "ArcRotateCameraPointersInput";
  47384. };
  47385. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47386. return "pointers";
  47387. };
  47388. __decorate([
  47389. BABYLON.serialize()
  47390. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47391. __decorate([
  47392. BABYLON.serialize()
  47393. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47394. __decorate([
  47395. BABYLON.serialize()
  47396. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47397. __decorate([
  47398. BABYLON.serialize()
  47399. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47400. __decorate([
  47401. BABYLON.serialize()
  47402. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47403. __decorate([
  47404. BABYLON.serialize()
  47405. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47406. __decorate([
  47407. BABYLON.serialize()
  47408. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47409. __decorate([
  47410. BABYLON.serialize()
  47411. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47412. return ArcRotateCameraPointersInput;
  47413. }());
  47414. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47415. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47416. })(BABYLON || (BABYLON = {}));
  47417. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47418. var BABYLON;
  47419. (function (BABYLON) {
  47420. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47421. __extends(ArcRotateCameraInputsManager, _super);
  47422. function ArcRotateCameraInputsManager(camera) {
  47423. return _super.call(this, camera) || this;
  47424. }
  47425. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47426. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47427. return this;
  47428. };
  47429. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47430. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47431. return this;
  47432. };
  47433. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47434. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47435. return this;
  47436. };
  47437. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47438. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47439. return this;
  47440. };
  47441. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47442. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47443. return this;
  47444. };
  47445. return ArcRotateCameraInputsManager;
  47446. }(BABYLON.CameraInputsManager));
  47447. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47448. })(BABYLON || (BABYLON = {}));
  47449. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47450. var BABYLON;
  47451. (function (BABYLON) {
  47452. var ArcRotateCamera = /** @class */ (function (_super) {
  47453. __extends(ArcRotateCamera, _super);
  47454. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47455. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47456. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47457. _this.inertialAlphaOffset = 0;
  47458. _this.inertialBetaOffset = 0;
  47459. _this.inertialRadiusOffset = 0;
  47460. _this.lowerAlphaLimit = null;
  47461. _this.upperAlphaLimit = null;
  47462. _this.lowerBetaLimit = 0.01;
  47463. _this.upperBetaLimit = Math.PI;
  47464. _this.lowerRadiusLimit = null;
  47465. _this.upperRadiusLimit = null;
  47466. _this.inertialPanningX = 0;
  47467. _this.inertialPanningY = 0;
  47468. _this.pinchToPanMaxDistance = 20;
  47469. _this.panningDistanceLimit = null;
  47470. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47471. _this.panningInertia = 0.9;
  47472. //-- end properties for backward compatibility for inputs
  47473. _this.zoomOnFactor = 1;
  47474. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47475. _this.allowUpsideDown = true;
  47476. _this._viewMatrix = new BABYLON.Matrix();
  47477. // Panning
  47478. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47479. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47480. _this.checkCollisions = false;
  47481. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47482. _this._previousPosition = BABYLON.Vector3.Zero();
  47483. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47484. _this._newPosition = BABYLON.Vector3.Zero();
  47485. _this._computationVector = BABYLON.Vector3.Zero();
  47486. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47487. if (collidedMesh === void 0) { collidedMesh = null; }
  47488. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47489. newPosition.multiplyInPlace(_this._collider._radius);
  47490. }
  47491. if (!collidedMesh) {
  47492. _this._previousPosition.copyFrom(_this.position);
  47493. }
  47494. else {
  47495. _this.setPosition(newPosition);
  47496. if (_this.onCollide) {
  47497. _this.onCollide(collidedMesh);
  47498. }
  47499. }
  47500. // Recompute because of constraints
  47501. var cosa = Math.cos(_this.alpha);
  47502. var sina = Math.sin(_this.alpha);
  47503. var cosb = Math.cos(_this.beta);
  47504. var sinb = Math.sin(_this.beta);
  47505. if (sinb === 0) {
  47506. sinb = 0.0001;
  47507. }
  47508. var target = _this._getTargetPosition();
  47509. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47510. target.addToRef(_this._computationVector, _this._newPosition);
  47511. _this.position.copyFrom(_this._newPosition);
  47512. var up = _this.upVector;
  47513. if (_this.allowUpsideDown && _this.beta < 0) {
  47514. up = up.clone();
  47515. up = up.negate();
  47516. }
  47517. _this._computeViewMatrix(_this.position, target, up);
  47518. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47519. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47520. _this._collisionTriggered = false;
  47521. };
  47522. _this._target = BABYLON.Vector3.Zero();
  47523. if (target) {
  47524. _this.setTarget(target);
  47525. }
  47526. _this.alpha = alpha;
  47527. _this.beta = beta;
  47528. _this.radius = radius;
  47529. _this.getViewMatrix();
  47530. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47531. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47532. return _this;
  47533. }
  47534. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47535. get: function () {
  47536. return this._target;
  47537. },
  47538. set: function (value) {
  47539. this.setTarget(value);
  47540. },
  47541. enumerable: true,
  47542. configurable: true
  47543. });
  47544. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47545. //-- begin properties for backward compatibility for inputs
  47546. get: function () {
  47547. var pointers = this.inputs.attached["pointers"];
  47548. if (pointers)
  47549. return pointers.angularSensibilityX;
  47550. return 0;
  47551. },
  47552. set: function (value) {
  47553. var pointers = this.inputs.attached["pointers"];
  47554. if (pointers) {
  47555. pointers.angularSensibilityX = value;
  47556. }
  47557. },
  47558. enumerable: true,
  47559. configurable: true
  47560. });
  47561. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47562. get: function () {
  47563. var pointers = this.inputs.attached["pointers"];
  47564. if (pointers)
  47565. return pointers.angularSensibilityY;
  47566. return 0;
  47567. },
  47568. set: function (value) {
  47569. var pointers = this.inputs.attached["pointers"];
  47570. if (pointers) {
  47571. pointers.angularSensibilityY = value;
  47572. }
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47578. get: function () {
  47579. var pointers = this.inputs.attached["pointers"];
  47580. if (pointers)
  47581. return pointers.pinchPrecision;
  47582. return 0;
  47583. },
  47584. set: function (value) {
  47585. var pointers = this.inputs.attached["pointers"];
  47586. if (pointers) {
  47587. pointers.pinchPrecision = value;
  47588. }
  47589. },
  47590. enumerable: true,
  47591. configurable: true
  47592. });
  47593. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47594. get: function () {
  47595. var pointers = this.inputs.attached["pointers"];
  47596. if (pointers)
  47597. return pointers.pinchDeltaPercentage;
  47598. return 0;
  47599. },
  47600. set: function (value) {
  47601. var pointers = this.inputs.attached["pointers"];
  47602. if (pointers) {
  47603. pointers.pinchDeltaPercentage = value;
  47604. }
  47605. },
  47606. enumerable: true,
  47607. configurable: true
  47608. });
  47609. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47610. get: function () {
  47611. var pointers = this.inputs.attached["pointers"];
  47612. if (pointers)
  47613. return pointers.panningSensibility;
  47614. return 0;
  47615. },
  47616. set: function (value) {
  47617. var pointers = this.inputs.attached["pointers"];
  47618. if (pointers) {
  47619. pointers.panningSensibility = value;
  47620. }
  47621. },
  47622. enumerable: true,
  47623. configurable: true
  47624. });
  47625. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47626. get: function () {
  47627. var keyboard = this.inputs.attached["keyboard"];
  47628. if (keyboard)
  47629. return keyboard.keysUp;
  47630. return [];
  47631. },
  47632. set: function (value) {
  47633. var keyboard = this.inputs.attached["keyboard"];
  47634. if (keyboard)
  47635. keyboard.keysUp = value;
  47636. },
  47637. enumerable: true,
  47638. configurable: true
  47639. });
  47640. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47641. get: function () {
  47642. var keyboard = this.inputs.attached["keyboard"];
  47643. if (keyboard)
  47644. return keyboard.keysDown;
  47645. return [];
  47646. },
  47647. set: function (value) {
  47648. var keyboard = this.inputs.attached["keyboard"];
  47649. if (keyboard)
  47650. keyboard.keysDown = value;
  47651. },
  47652. enumerable: true,
  47653. configurable: true
  47654. });
  47655. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47656. get: function () {
  47657. var keyboard = this.inputs.attached["keyboard"];
  47658. if (keyboard)
  47659. return keyboard.keysLeft;
  47660. return [];
  47661. },
  47662. set: function (value) {
  47663. var keyboard = this.inputs.attached["keyboard"];
  47664. if (keyboard)
  47665. keyboard.keysLeft = value;
  47666. },
  47667. enumerable: true,
  47668. configurable: true
  47669. });
  47670. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47671. get: function () {
  47672. var keyboard = this.inputs.attached["keyboard"];
  47673. if (keyboard)
  47674. return keyboard.keysRight;
  47675. return [];
  47676. },
  47677. set: function (value) {
  47678. var keyboard = this.inputs.attached["keyboard"];
  47679. if (keyboard)
  47680. keyboard.keysRight = value;
  47681. },
  47682. enumerable: true,
  47683. configurable: true
  47684. });
  47685. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47686. get: function () {
  47687. var mousewheel = this.inputs.attached["mousewheel"];
  47688. if (mousewheel)
  47689. return mousewheel.wheelPrecision;
  47690. return 0;
  47691. },
  47692. set: function (value) {
  47693. var mousewheel = this.inputs.attached["mousewheel"];
  47694. if (mousewheel)
  47695. mousewheel.wheelPrecision = value;
  47696. },
  47697. enumerable: true,
  47698. configurable: true
  47699. });
  47700. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47701. get: function () {
  47702. var mousewheel = this.inputs.attached["mousewheel"];
  47703. if (mousewheel)
  47704. return mousewheel.wheelDeltaPercentage;
  47705. return 0;
  47706. },
  47707. set: function (value) {
  47708. var mousewheel = this.inputs.attached["mousewheel"];
  47709. if (mousewheel)
  47710. mousewheel.wheelDeltaPercentage = value;
  47711. },
  47712. enumerable: true,
  47713. configurable: true
  47714. });
  47715. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47716. get: function () {
  47717. return this._bouncingBehavior;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47723. get: function () {
  47724. return this._bouncingBehavior != null;
  47725. },
  47726. set: function (value) {
  47727. if (value === this.useBouncingBehavior) {
  47728. return;
  47729. }
  47730. if (value) {
  47731. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47732. this.addBehavior(this._bouncingBehavior);
  47733. }
  47734. else if (this._bouncingBehavior) {
  47735. this.removeBehavior(this._bouncingBehavior);
  47736. this._bouncingBehavior = null;
  47737. }
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47743. get: function () {
  47744. return this._framingBehavior;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47750. get: function () {
  47751. return this._framingBehavior != null;
  47752. },
  47753. set: function (value) {
  47754. if (value === this.useFramingBehavior) {
  47755. return;
  47756. }
  47757. if (value) {
  47758. this._framingBehavior = new BABYLON.FramingBehavior();
  47759. this.addBehavior(this._framingBehavior);
  47760. }
  47761. else if (this._framingBehavior) {
  47762. this.removeBehavior(this._framingBehavior);
  47763. this._framingBehavior = null;
  47764. }
  47765. },
  47766. enumerable: true,
  47767. configurable: true
  47768. });
  47769. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47770. get: function () {
  47771. return this._autoRotationBehavior;
  47772. },
  47773. enumerable: true,
  47774. configurable: true
  47775. });
  47776. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47777. get: function () {
  47778. return this._autoRotationBehavior != null;
  47779. },
  47780. set: function (value) {
  47781. if (value === this.useAutoRotationBehavior) {
  47782. return;
  47783. }
  47784. if (value) {
  47785. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47786. this.addBehavior(this._autoRotationBehavior);
  47787. }
  47788. else if (this._autoRotationBehavior) {
  47789. this.removeBehavior(this._autoRotationBehavior);
  47790. this._autoRotationBehavior = null;
  47791. }
  47792. },
  47793. enumerable: true,
  47794. configurable: true
  47795. });
  47796. // Cache
  47797. ArcRotateCamera.prototype._initCache = function () {
  47798. _super.prototype._initCache.call(this);
  47799. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47800. this._cache.alpha = undefined;
  47801. this._cache.beta = undefined;
  47802. this._cache.radius = undefined;
  47803. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47804. };
  47805. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47806. if (!ignoreParentClass) {
  47807. _super.prototype._updateCache.call(this);
  47808. }
  47809. this._cache._target.copyFrom(this._getTargetPosition());
  47810. this._cache.alpha = this.alpha;
  47811. this._cache.beta = this.beta;
  47812. this._cache.radius = this.radius;
  47813. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47814. };
  47815. ArcRotateCamera.prototype._getTargetPosition = function () {
  47816. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47817. var pos = this._targetHost.getAbsolutePosition();
  47818. if (this._targetBoundingCenter) {
  47819. pos.addToRef(this._targetBoundingCenter, this._target);
  47820. }
  47821. else {
  47822. this._target.copyFrom(pos);
  47823. }
  47824. }
  47825. var lockedTargetPosition = this._getLockedTargetPosition();
  47826. if (lockedTargetPosition) {
  47827. return lockedTargetPosition;
  47828. }
  47829. return this._target;
  47830. };
  47831. ArcRotateCamera.prototype.storeState = function () {
  47832. this._storedAlpha = this.alpha;
  47833. this._storedBeta = this.beta;
  47834. this._storedRadius = this.radius;
  47835. this._storedTarget = this._getTargetPosition().clone();
  47836. return _super.prototype.storeState.call(this);
  47837. };
  47838. /**
  47839. * Restored camera state. You must call storeState() first
  47840. */
  47841. ArcRotateCamera.prototype._restoreStateValues = function () {
  47842. if (!_super.prototype._restoreStateValues.call(this)) {
  47843. return false;
  47844. }
  47845. this.alpha = this._storedAlpha;
  47846. this.beta = this._storedBeta;
  47847. this.radius = this._storedRadius;
  47848. this.setTarget(this._storedTarget.clone());
  47849. this.inertialAlphaOffset = 0;
  47850. this.inertialBetaOffset = 0;
  47851. this.inertialRadiusOffset = 0;
  47852. this.inertialPanningX = 0;
  47853. this.inertialPanningY = 0;
  47854. return true;
  47855. };
  47856. // Synchronized
  47857. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47858. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47859. return false;
  47860. return this._cache._target.equals(this._getTargetPosition())
  47861. && this._cache.alpha === this.alpha
  47862. && this._cache.beta === this.beta
  47863. && this._cache.radius === this.radius
  47864. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47865. };
  47866. // Methods
  47867. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47868. var _this = this;
  47869. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47870. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47871. this._useCtrlForPanning = useCtrlForPanning;
  47872. this._panningMouseButton = panningMouseButton;
  47873. this.inputs.attachElement(element, noPreventDefault);
  47874. this._reset = function () {
  47875. _this.inertialAlphaOffset = 0;
  47876. _this.inertialBetaOffset = 0;
  47877. _this.inertialRadiusOffset = 0;
  47878. _this.inertialPanningX = 0;
  47879. _this.inertialPanningY = 0;
  47880. };
  47881. };
  47882. ArcRotateCamera.prototype.detachControl = function (element) {
  47883. this.inputs.detachElement(element);
  47884. if (this._reset) {
  47885. this._reset();
  47886. }
  47887. };
  47888. ArcRotateCamera.prototype._checkInputs = function () {
  47889. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47890. if (this._collisionTriggered) {
  47891. return;
  47892. }
  47893. this.inputs.checkInputs();
  47894. // Inertia
  47895. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47896. var inertialAlphaOffset = this.inertialAlphaOffset;
  47897. if (this.beta <= 0)
  47898. inertialAlphaOffset *= -1;
  47899. if (this.getScene().useRightHandedSystem)
  47900. inertialAlphaOffset *= -1;
  47901. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47902. inertialAlphaOffset *= -1;
  47903. this.alpha += inertialAlphaOffset;
  47904. this.beta += this.inertialBetaOffset;
  47905. this.radius -= this.inertialRadiusOffset;
  47906. this.inertialAlphaOffset *= this.inertia;
  47907. this.inertialBetaOffset *= this.inertia;
  47908. this.inertialRadiusOffset *= this.inertia;
  47909. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47910. this.inertialAlphaOffset = 0;
  47911. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47912. this.inertialBetaOffset = 0;
  47913. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47914. this.inertialRadiusOffset = 0;
  47915. }
  47916. // Panning inertia
  47917. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  47918. if (!this._localDirection) {
  47919. this._localDirection = BABYLON.Vector3.Zero();
  47920. this._transformedDirection = BABYLON.Vector3.Zero();
  47921. }
  47922. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  47923. this._localDirection.multiplyInPlace(this.panningAxis);
  47924. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  47925. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  47926. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  47927. if (!this.panningAxis.y) {
  47928. this._transformedDirection.y = 0;
  47929. }
  47930. if (!this._targetHost) {
  47931. if (this.panningDistanceLimit) {
  47932. this._transformedDirection.addInPlace(this._target);
  47933. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  47934. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  47935. this._target.copyFrom(this._transformedDirection);
  47936. }
  47937. }
  47938. else {
  47939. this._target.addInPlace(this._transformedDirection);
  47940. }
  47941. }
  47942. this.inertialPanningX *= this.panningInertia;
  47943. this.inertialPanningY *= this.panningInertia;
  47944. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  47945. this.inertialPanningX = 0;
  47946. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  47947. this.inertialPanningY = 0;
  47948. }
  47949. // Limits
  47950. this._checkLimits();
  47951. _super.prototype._checkInputs.call(this);
  47952. };
  47953. ArcRotateCamera.prototype._checkLimits = function () {
  47954. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  47955. if (this.allowUpsideDown && this.beta > Math.PI) {
  47956. this.beta = this.beta - (2 * Math.PI);
  47957. }
  47958. }
  47959. else {
  47960. if (this.beta < this.lowerBetaLimit) {
  47961. this.beta = this.lowerBetaLimit;
  47962. }
  47963. }
  47964. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  47965. if (this.allowUpsideDown && this.beta < -Math.PI) {
  47966. this.beta = this.beta + (2 * Math.PI);
  47967. }
  47968. }
  47969. else {
  47970. if (this.beta > this.upperBetaLimit) {
  47971. this.beta = this.upperBetaLimit;
  47972. }
  47973. }
  47974. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  47975. this.alpha = this.lowerAlphaLimit;
  47976. }
  47977. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  47978. this.alpha = this.upperAlphaLimit;
  47979. }
  47980. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  47981. this.radius = this.lowerRadiusLimit;
  47982. }
  47983. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  47984. this.radius = this.upperRadiusLimit;
  47985. }
  47986. };
  47987. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  47988. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  47989. this.radius = this._computationVector.length();
  47990. if (this.radius === 0) {
  47991. this.radius = 0.0001; // Just to avoid division by zero
  47992. }
  47993. // Alpha
  47994. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  47995. if (this._computationVector.z < 0) {
  47996. this.alpha = 2 * Math.PI - this.alpha;
  47997. }
  47998. // Beta
  47999. this.beta = Math.acos(this._computationVector.y / this.radius);
  48000. this._checkLimits();
  48001. };
  48002. ArcRotateCamera.prototype.setPosition = function (position) {
  48003. if (this.position.equals(position)) {
  48004. return;
  48005. }
  48006. this.position.copyFrom(position);
  48007. this.rebuildAnglesAndRadius();
  48008. };
  48009. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48010. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48011. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48012. if (target.getBoundingInfo) {
  48013. if (toBoundingCenter) {
  48014. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48015. }
  48016. else {
  48017. this._targetBoundingCenter = null;
  48018. }
  48019. this._targetHost = target;
  48020. this._target = this._getTargetPosition();
  48021. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48022. }
  48023. else {
  48024. var newTarget = target;
  48025. var currentTarget = this._getTargetPosition();
  48026. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48027. return;
  48028. }
  48029. this._targetHost = null;
  48030. this._target = newTarget;
  48031. this._targetBoundingCenter = null;
  48032. this.onMeshTargetChangedObservable.notifyObservers(null);
  48033. }
  48034. this.rebuildAnglesAndRadius();
  48035. };
  48036. ArcRotateCamera.prototype._getViewMatrix = function () {
  48037. // Compute
  48038. var cosa = Math.cos(this.alpha);
  48039. var sina = Math.sin(this.alpha);
  48040. var cosb = Math.cos(this.beta);
  48041. var sinb = Math.sin(this.beta);
  48042. if (sinb === 0) {
  48043. sinb = 0.0001;
  48044. }
  48045. var target = this._getTargetPosition();
  48046. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48047. target.addToRef(this._computationVector, this._newPosition);
  48048. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48049. if (!this._collider) {
  48050. this._collider = new BABYLON.Collider();
  48051. }
  48052. this._collider._radius = this.collisionRadius;
  48053. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48054. this._collisionTriggered = true;
  48055. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48056. }
  48057. else {
  48058. this.position.copyFrom(this._newPosition);
  48059. var up = this.upVector;
  48060. if (this.allowUpsideDown && sinb < 0) {
  48061. up = up.clone();
  48062. up = up.negate();
  48063. }
  48064. this._computeViewMatrix(this.position, target, up);
  48065. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48066. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48067. }
  48068. this._currentTarget = target;
  48069. return this._viewMatrix;
  48070. };
  48071. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48072. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48073. meshes = meshes || this.getScene().meshes;
  48074. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48075. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48076. this.radius = distance * this.zoomOnFactor;
  48077. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48078. };
  48079. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48080. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48081. var meshesOrMinMaxVector;
  48082. var distance;
  48083. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48084. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48085. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48086. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48087. }
  48088. else { //minMaxVector and distance
  48089. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48090. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48091. distance = minMaxVectorAndDistance.distance;
  48092. }
  48093. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48094. if (!doNotUpdateMaxZ) {
  48095. this.maxZ = distance * 2;
  48096. }
  48097. };
  48098. /**
  48099. * @override
  48100. * Override Camera.createRigCamera
  48101. */
  48102. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48103. var alphaShift = 0;
  48104. switch (this.cameraRigMode) {
  48105. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48106. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48107. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48108. case BABYLON.Camera.RIG_MODE_VR:
  48109. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48110. break;
  48111. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48112. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48113. break;
  48114. }
  48115. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48116. rigCam._cameraRigParams = {};
  48117. return rigCam;
  48118. };
  48119. /**
  48120. * @override
  48121. * Override Camera._updateRigCameras
  48122. */
  48123. ArcRotateCamera.prototype._updateRigCameras = function () {
  48124. var camLeft = this._rigCameras[0];
  48125. var camRight = this._rigCameras[1];
  48126. camLeft.beta = camRight.beta = this.beta;
  48127. camLeft.radius = camRight.radius = this.radius;
  48128. switch (this.cameraRigMode) {
  48129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48130. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48131. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48132. case BABYLON.Camera.RIG_MODE_VR:
  48133. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48134. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48135. break;
  48136. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48137. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48138. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48139. break;
  48140. }
  48141. _super.prototype._updateRigCameras.call(this);
  48142. };
  48143. ArcRotateCamera.prototype.dispose = function () {
  48144. this.inputs.clear();
  48145. _super.prototype.dispose.call(this);
  48146. };
  48147. ArcRotateCamera.prototype.getClassName = function () {
  48148. return "ArcRotateCamera";
  48149. };
  48150. __decorate([
  48151. BABYLON.serialize()
  48152. ], ArcRotateCamera.prototype, "alpha", void 0);
  48153. __decorate([
  48154. BABYLON.serialize()
  48155. ], ArcRotateCamera.prototype, "beta", void 0);
  48156. __decorate([
  48157. BABYLON.serialize()
  48158. ], ArcRotateCamera.prototype, "radius", void 0);
  48159. __decorate([
  48160. BABYLON.serializeAsVector3("target")
  48161. ], ArcRotateCamera.prototype, "_target", void 0);
  48162. __decorate([
  48163. BABYLON.serialize()
  48164. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48165. __decorate([
  48166. BABYLON.serialize()
  48167. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48168. __decorate([
  48169. BABYLON.serialize()
  48170. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48171. __decorate([
  48172. BABYLON.serialize()
  48173. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48174. __decorate([
  48175. BABYLON.serialize()
  48176. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48177. __decorate([
  48178. BABYLON.serialize()
  48179. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48180. __decorate([
  48181. BABYLON.serialize()
  48182. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48183. __decorate([
  48184. BABYLON.serialize()
  48185. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48186. __decorate([
  48187. BABYLON.serialize()
  48188. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48189. __decorate([
  48190. BABYLON.serialize()
  48191. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48192. __decorate([
  48193. BABYLON.serialize()
  48194. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48195. __decorate([
  48196. BABYLON.serialize()
  48197. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48198. __decorate([
  48199. BABYLON.serialize()
  48200. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48201. __decorate([
  48202. BABYLON.serializeAsVector3()
  48203. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48204. __decorate([
  48205. BABYLON.serialize()
  48206. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48207. __decorate([
  48208. BABYLON.serialize()
  48209. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48210. __decorate([
  48211. BABYLON.serialize()
  48212. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48213. return ArcRotateCamera;
  48214. }(BABYLON.TargetCamera));
  48215. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48216. })(BABYLON || (BABYLON = {}));
  48217. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48218. var BABYLON;
  48219. (function (BABYLON) {
  48220. /**
  48221. * The HemisphericLight simulates the ambient environment light,
  48222. * so the passed direction is the light reflection direction, not the incoming direction.
  48223. */
  48224. var HemisphericLight = /** @class */ (function (_super) {
  48225. __extends(HemisphericLight, _super);
  48226. /**
  48227. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48228. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48229. * The HemisphericLight can't cast shadows.
  48230. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48231. * @param name The friendly name of the light
  48232. * @param direction The direction of the light reflection
  48233. * @param scene The scene the light belongs to
  48234. */
  48235. function HemisphericLight(name, direction, scene) {
  48236. var _this = _super.call(this, name, scene) || this;
  48237. /**
  48238. * The groundColor is the light in the opposite direction to the one specified during creation.
  48239. * 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.
  48240. */
  48241. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48242. _this.direction = direction || BABYLON.Vector3.Up();
  48243. return _this;
  48244. }
  48245. HemisphericLight.prototype._buildUniformLayout = function () {
  48246. this._uniformBuffer.addUniform("vLightData", 4);
  48247. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48248. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48249. this._uniformBuffer.addUniform("vLightGround", 3);
  48250. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48251. this._uniformBuffer.addUniform("depthValues", 2);
  48252. this._uniformBuffer.create();
  48253. };
  48254. /**
  48255. * Returns the string "HemisphericLight".
  48256. * @return The class name
  48257. */
  48258. HemisphericLight.prototype.getClassName = function () {
  48259. return "HemisphericLight";
  48260. };
  48261. /**
  48262. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48263. * Returns the updated direction.
  48264. * @param target The target the direction should point to
  48265. * @return The computed direction
  48266. */
  48267. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48268. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48269. return this.direction;
  48270. };
  48271. /**
  48272. * Returns the shadow generator associated to the light.
  48273. * @returns Always null for hemispheric lights because it does not support shadows.
  48274. */
  48275. HemisphericLight.prototype.getShadowGenerator = function () {
  48276. return null;
  48277. };
  48278. /**
  48279. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48280. * @param effect The effect to update
  48281. * @param lightIndex The index of the light in the effect to update
  48282. * @returns The hemispheric light
  48283. */
  48284. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48285. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48286. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48287. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48288. return this;
  48289. };
  48290. /**
  48291. * @hidden internal use only.
  48292. */
  48293. HemisphericLight.prototype._getWorldMatrix = function () {
  48294. if (!this._worldMatrix) {
  48295. this._worldMatrix = BABYLON.Matrix.Identity();
  48296. }
  48297. return this._worldMatrix;
  48298. };
  48299. /**
  48300. * Returns the integer 3.
  48301. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48302. */
  48303. HemisphericLight.prototype.getTypeID = function () {
  48304. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48305. };
  48306. __decorate([
  48307. BABYLON.serializeAsColor3()
  48308. ], HemisphericLight.prototype, "groundColor", void 0);
  48309. __decorate([
  48310. BABYLON.serializeAsVector3()
  48311. ], HemisphericLight.prototype, "direction", void 0);
  48312. return HemisphericLight;
  48313. }(BABYLON.Light));
  48314. BABYLON.HemisphericLight = HemisphericLight;
  48315. })(BABYLON || (BABYLON = {}));
  48316. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48317. var BABYLON;
  48318. (function (BABYLON) {
  48319. /**
  48320. * Base implementation IShadowLight
  48321. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48322. */
  48323. var ShadowLight = /** @class */ (function (_super) {
  48324. __extends(ShadowLight, _super);
  48325. function ShadowLight() {
  48326. var _this = _super !== null && _super.apply(this, arguments) || this;
  48327. _this._needProjectionMatrixCompute = true;
  48328. return _this;
  48329. }
  48330. ShadowLight.prototype._setPosition = function (value) {
  48331. this._position = value;
  48332. };
  48333. Object.defineProperty(ShadowLight.prototype, "position", {
  48334. /**
  48335. * Sets the position the shadow will be casted from. Also use as the light position for both
  48336. * point and spot lights.
  48337. */
  48338. get: function () {
  48339. return this._position;
  48340. },
  48341. /**
  48342. * Sets the position the shadow will be casted from. Also use as the light position for both
  48343. * point and spot lights.
  48344. */
  48345. set: function (value) {
  48346. this._setPosition(value);
  48347. },
  48348. enumerable: true,
  48349. configurable: true
  48350. });
  48351. ShadowLight.prototype._setDirection = function (value) {
  48352. this._direction = value;
  48353. };
  48354. Object.defineProperty(ShadowLight.prototype, "direction", {
  48355. /**
  48356. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48357. * Also use as the light direction on spot and directional lights.
  48358. */
  48359. get: function () {
  48360. return this._direction;
  48361. },
  48362. /**
  48363. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48364. * Also use as the light direction on spot and directional lights.
  48365. */
  48366. set: function (value) {
  48367. this._setDirection(value);
  48368. },
  48369. enumerable: true,
  48370. configurable: true
  48371. });
  48372. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48373. /**
  48374. * Gets the shadow projection clipping minimum z value.
  48375. */
  48376. get: function () {
  48377. return this._shadowMinZ;
  48378. },
  48379. /**
  48380. * Sets the shadow projection clipping minimum z value.
  48381. */
  48382. set: function (value) {
  48383. this._shadowMinZ = value;
  48384. this.forceProjectionMatrixCompute();
  48385. },
  48386. enumerable: true,
  48387. configurable: true
  48388. });
  48389. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48390. /**
  48391. * Sets the shadow projection clipping maximum z value.
  48392. */
  48393. get: function () {
  48394. return this._shadowMaxZ;
  48395. },
  48396. /**
  48397. * Gets the shadow projection clipping maximum z value.
  48398. */
  48399. set: function (value) {
  48400. this._shadowMaxZ = value;
  48401. this.forceProjectionMatrixCompute();
  48402. },
  48403. enumerable: true,
  48404. configurable: true
  48405. });
  48406. /**
  48407. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48408. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48409. */
  48410. ShadowLight.prototype.computeTransformedInformation = function () {
  48411. if (this.parent && this.parent.getWorldMatrix) {
  48412. if (!this.transformedPosition) {
  48413. this.transformedPosition = BABYLON.Vector3.Zero();
  48414. }
  48415. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48416. // In case the direction is present.
  48417. if (this.direction) {
  48418. if (!this.transformedDirection) {
  48419. this.transformedDirection = BABYLON.Vector3.Zero();
  48420. }
  48421. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48422. }
  48423. return true;
  48424. }
  48425. return false;
  48426. };
  48427. /**
  48428. * Return the depth scale used for the shadow map.
  48429. * @returns the depth scale.
  48430. */
  48431. ShadowLight.prototype.getDepthScale = function () {
  48432. return 50.0;
  48433. };
  48434. /**
  48435. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48436. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48437. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48438. */
  48439. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48440. return this.transformedDirection ? this.transformedDirection : this.direction;
  48441. };
  48442. /**
  48443. * Returns the ShadowLight absolute position in the World.
  48444. * @returns the position vector in world space
  48445. */
  48446. ShadowLight.prototype.getAbsolutePosition = function () {
  48447. return this.transformedPosition ? this.transformedPosition : this.position;
  48448. };
  48449. /**
  48450. * Sets the ShadowLight direction toward the passed target.
  48451. * @param target The point tot target in local space
  48452. * @returns the updated ShadowLight direction
  48453. */
  48454. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48455. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48456. return this.direction;
  48457. };
  48458. /**
  48459. * Returns the light rotation in euler definition.
  48460. * @returns the x y z rotation in local space.
  48461. */
  48462. ShadowLight.prototype.getRotation = function () {
  48463. this.direction.normalize();
  48464. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48465. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48466. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48467. };
  48468. /**
  48469. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48470. * @returns true if a cube texture needs to be use
  48471. */
  48472. ShadowLight.prototype.needCube = function () {
  48473. return false;
  48474. };
  48475. /**
  48476. * Detects if the projection matrix requires to be recomputed this frame.
  48477. * @returns true if it requires to be recomputed otherwise, false.
  48478. */
  48479. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48480. return this._needProjectionMatrixCompute;
  48481. };
  48482. /**
  48483. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48484. */
  48485. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48486. this._needProjectionMatrixCompute = true;
  48487. };
  48488. /**
  48489. * Get the world matrix of the sahdow lights.
  48490. * @hidden Internal Use Only
  48491. */
  48492. ShadowLight.prototype._getWorldMatrix = function () {
  48493. if (!this._worldMatrix) {
  48494. this._worldMatrix = BABYLON.Matrix.Identity();
  48495. }
  48496. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48497. return this._worldMatrix;
  48498. };
  48499. /**
  48500. * Gets the minZ used for shadow according to both the scene and the light.
  48501. * @param activeCamera The camera we are returning the min for
  48502. * @returns the depth min z
  48503. */
  48504. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48505. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48506. };
  48507. /**
  48508. * Gets the maxZ used for shadow according to both the scene and the light.
  48509. * @param activeCamera The camera we are returning the max for
  48510. * @returns the depth max z
  48511. */
  48512. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48513. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48514. };
  48515. /**
  48516. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48517. * @param matrix The materix to updated with the projection information
  48518. * @param viewMatrix The transform matrix of the light
  48519. * @param renderList The list of mesh to render in the map
  48520. * @returns The current light
  48521. */
  48522. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48523. if (this.customProjectionMatrixBuilder) {
  48524. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48525. }
  48526. else {
  48527. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48528. }
  48529. return this;
  48530. };
  48531. __decorate([
  48532. BABYLON.serializeAsVector3()
  48533. ], ShadowLight.prototype, "position", null);
  48534. __decorate([
  48535. BABYLON.serializeAsVector3()
  48536. ], ShadowLight.prototype, "direction", null);
  48537. __decorate([
  48538. BABYLON.serialize()
  48539. ], ShadowLight.prototype, "shadowMinZ", null);
  48540. __decorate([
  48541. BABYLON.serialize()
  48542. ], ShadowLight.prototype, "shadowMaxZ", null);
  48543. return ShadowLight;
  48544. }(BABYLON.Light));
  48545. BABYLON.ShadowLight = ShadowLight;
  48546. })(BABYLON || (BABYLON = {}));
  48547. //# sourceMappingURL=babylon.shadowLight.js.map
  48548. var BABYLON;
  48549. (function (BABYLON) {
  48550. /**
  48551. * A point light is a light defined by an unique point in world space.
  48552. * The light is emitted in every direction from this point.
  48553. * A good example of a point light is a standard light bulb.
  48554. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48555. */
  48556. var PointLight = /** @class */ (function (_super) {
  48557. __extends(PointLight, _super);
  48558. /**
  48559. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48560. * A PointLight emits the light in every direction.
  48561. * It can cast shadows.
  48562. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48563. * ```javascript
  48564. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48565. * ```
  48566. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48567. * @param name The light friendly name
  48568. * @param position The position of the point light in the scene
  48569. * @param scene The scene the lights belongs to
  48570. */
  48571. function PointLight(name, position, scene) {
  48572. var _this = _super.call(this, name, scene) || this;
  48573. _this._shadowAngle = Math.PI / 2;
  48574. _this.position = position;
  48575. return _this;
  48576. }
  48577. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48578. /**
  48579. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48580. * This specifies what angle the shadow will use to be created.
  48581. *
  48582. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48583. */
  48584. get: function () {
  48585. return this._shadowAngle;
  48586. },
  48587. /**
  48588. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48589. * This specifies what angle the shadow will use to be created.
  48590. *
  48591. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48592. */
  48593. set: function (value) {
  48594. this._shadowAngle = value;
  48595. this.forceProjectionMatrixCompute();
  48596. },
  48597. enumerable: true,
  48598. configurable: true
  48599. });
  48600. Object.defineProperty(PointLight.prototype, "direction", {
  48601. /**
  48602. * Gets the direction if it has been set.
  48603. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48604. */
  48605. get: function () {
  48606. return this._direction;
  48607. },
  48608. /**
  48609. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48610. */
  48611. set: function (value) {
  48612. var previousNeedCube = this.needCube();
  48613. this._direction = value;
  48614. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48615. this._shadowGenerator.recreateShadowMap();
  48616. }
  48617. },
  48618. enumerable: true,
  48619. configurable: true
  48620. });
  48621. /**
  48622. * Returns the string "PointLight"
  48623. * @returns the class name
  48624. */
  48625. PointLight.prototype.getClassName = function () {
  48626. return "PointLight";
  48627. };
  48628. /**
  48629. * Returns the integer 0.
  48630. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48631. */
  48632. PointLight.prototype.getTypeID = function () {
  48633. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48634. };
  48635. /**
  48636. * Specifies wether or not the shadowmap should be a cube texture.
  48637. * @returns true if the shadowmap needs to be a cube texture.
  48638. */
  48639. PointLight.prototype.needCube = function () {
  48640. return !this.direction;
  48641. };
  48642. /**
  48643. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48644. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48645. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48646. */
  48647. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48648. if (this.direction) {
  48649. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48650. }
  48651. else {
  48652. switch (faceIndex) {
  48653. case 0:
  48654. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48655. case 1:
  48656. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48657. case 2:
  48658. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48659. case 3:
  48660. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48661. case 4:
  48662. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48663. case 5:
  48664. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48665. }
  48666. }
  48667. return BABYLON.Vector3.Zero();
  48668. };
  48669. /**
  48670. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48671. * - fov = PI / 2
  48672. * - aspect ratio : 1.0
  48673. * - z-near and far equal to the active camera minZ and maxZ.
  48674. * Returns the PointLight.
  48675. */
  48676. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48677. var activeCamera = this.getScene().activeCamera;
  48678. if (!activeCamera) {
  48679. return;
  48680. }
  48681. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48682. };
  48683. PointLight.prototype._buildUniformLayout = function () {
  48684. this._uniformBuffer.addUniform("vLightData", 4);
  48685. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48686. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48687. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48688. this._uniformBuffer.addUniform("depthValues", 2);
  48689. this._uniformBuffer.create();
  48690. };
  48691. /**
  48692. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48693. * @param effect The effect to update
  48694. * @param lightIndex The index of the light in the effect to update
  48695. * @returns The point light
  48696. */
  48697. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48698. if (this.computeTransformedInformation()) {
  48699. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48700. return this;
  48701. }
  48702. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48703. return this;
  48704. };
  48705. __decorate([
  48706. BABYLON.serialize()
  48707. ], PointLight.prototype, "shadowAngle", null);
  48708. return PointLight;
  48709. }(BABYLON.ShadowLight));
  48710. BABYLON.PointLight = PointLight;
  48711. })(BABYLON || (BABYLON = {}));
  48712. //# sourceMappingURL=babylon.pointLight.js.map
  48713. var BABYLON;
  48714. (function (BABYLON) {
  48715. /**
  48716. * A directional light is defined by a direction (what a surprise!).
  48717. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48718. * 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.
  48719. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48720. */
  48721. var DirectionalLight = /** @class */ (function (_super) {
  48722. __extends(DirectionalLight, _super);
  48723. /**
  48724. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48725. * The directional light is emitted from everywhere in the given direction.
  48726. * It can cast shawdows.
  48727. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48728. * @param name The friendly name of the light
  48729. * @param direction The direction of the light
  48730. * @param scene The scene the light belongs to
  48731. */
  48732. function DirectionalLight(name, direction, scene) {
  48733. var _this = _super.call(this, name, scene) || this;
  48734. _this._shadowFrustumSize = 0;
  48735. _this._shadowOrthoScale = 0.1;
  48736. /**
  48737. * Automatically compute the projection matrix to best fit (including all the casters)
  48738. * on each frame.
  48739. */
  48740. _this.autoUpdateExtends = true;
  48741. // Cache
  48742. _this._orthoLeft = Number.MAX_VALUE;
  48743. _this._orthoRight = Number.MIN_VALUE;
  48744. _this._orthoTop = Number.MIN_VALUE;
  48745. _this._orthoBottom = Number.MAX_VALUE;
  48746. _this.position = direction.scale(-1.0);
  48747. _this.direction = direction;
  48748. return _this;
  48749. }
  48750. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48751. /**
  48752. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48753. */
  48754. get: function () {
  48755. return this._shadowFrustumSize;
  48756. },
  48757. /**
  48758. * Specifies a fix frustum size for the shadow generation.
  48759. */
  48760. set: function (value) {
  48761. this._shadowFrustumSize = value;
  48762. this.forceProjectionMatrixCompute();
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48768. /**
  48769. * Gets the shadow projection scale against the optimal computed one.
  48770. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48771. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48772. */
  48773. get: function () {
  48774. return this._shadowOrthoScale;
  48775. },
  48776. /**
  48777. * Sets the shadow projection scale against the optimal computed one.
  48778. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48779. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48780. */
  48781. set: function (value) {
  48782. this._shadowOrthoScale = value;
  48783. this.forceProjectionMatrixCompute();
  48784. },
  48785. enumerable: true,
  48786. configurable: true
  48787. });
  48788. /**
  48789. * Returns the string "DirectionalLight".
  48790. * @return The class name
  48791. */
  48792. DirectionalLight.prototype.getClassName = function () {
  48793. return "DirectionalLight";
  48794. };
  48795. /**
  48796. * Returns the integer 1.
  48797. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48798. */
  48799. DirectionalLight.prototype.getTypeID = function () {
  48800. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48801. };
  48802. /**
  48803. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48804. * Returns the DirectionalLight Shadow projection matrix.
  48805. */
  48806. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48807. if (this.shadowFrustumSize > 0) {
  48808. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48809. }
  48810. else {
  48811. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48812. }
  48813. };
  48814. /**
  48815. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48816. * Returns the DirectionalLight Shadow projection matrix.
  48817. */
  48818. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48819. var activeCamera = this.getScene().activeCamera;
  48820. if (!activeCamera) {
  48821. return;
  48822. }
  48823. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48824. };
  48825. /**
  48826. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48827. * Returns the DirectionalLight Shadow projection matrix.
  48828. */
  48829. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48830. var activeCamera = this.getScene().activeCamera;
  48831. if (!activeCamera) {
  48832. return;
  48833. }
  48834. // Check extends
  48835. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48836. var tempVector3 = BABYLON.Vector3.Zero();
  48837. this._orthoLeft = Number.MAX_VALUE;
  48838. this._orthoRight = Number.MIN_VALUE;
  48839. this._orthoTop = Number.MIN_VALUE;
  48840. this._orthoBottom = Number.MAX_VALUE;
  48841. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48842. var mesh = renderList[meshIndex];
  48843. if (!mesh) {
  48844. continue;
  48845. }
  48846. var boundingInfo = mesh.getBoundingInfo();
  48847. var boundingBox = boundingInfo.boundingBox;
  48848. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48849. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48850. if (tempVector3.x < this._orthoLeft)
  48851. this._orthoLeft = tempVector3.x;
  48852. if (tempVector3.y < this._orthoBottom)
  48853. this._orthoBottom = tempVector3.y;
  48854. if (tempVector3.x > this._orthoRight)
  48855. this._orthoRight = tempVector3.x;
  48856. if (tempVector3.y > this._orthoTop)
  48857. this._orthoTop = tempVector3.y;
  48858. }
  48859. }
  48860. }
  48861. var xOffset = this._orthoRight - this._orthoLeft;
  48862. var yOffset = this._orthoTop - this._orthoBottom;
  48863. 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);
  48864. };
  48865. DirectionalLight.prototype._buildUniformLayout = function () {
  48866. this._uniformBuffer.addUniform("vLightData", 4);
  48867. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48868. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48869. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48870. this._uniformBuffer.addUniform("depthValues", 2);
  48871. this._uniformBuffer.create();
  48872. };
  48873. /**
  48874. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48875. * @param effect The effect to update
  48876. * @param lightIndex The index of the light in the effect to update
  48877. * @returns The directional light
  48878. */
  48879. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48880. if (this.computeTransformedInformation()) {
  48881. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48882. return this;
  48883. }
  48884. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48885. return this;
  48886. };
  48887. /**
  48888. * Gets the minZ used for shadow according to both the scene and the light.
  48889. *
  48890. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48891. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48892. * @param activeCamera The camera we are returning the min for
  48893. * @returns the depth min z
  48894. */
  48895. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48896. return 1;
  48897. };
  48898. /**
  48899. * Gets the maxZ used for shadow according to both the scene and the light.
  48900. *
  48901. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48902. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48903. * @param activeCamera The camera we are returning the max for
  48904. * @returns the depth max z
  48905. */
  48906. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48907. return 1;
  48908. };
  48909. __decorate([
  48910. BABYLON.serialize()
  48911. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48912. __decorate([
  48913. BABYLON.serialize()
  48914. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48915. __decorate([
  48916. BABYLON.serialize()
  48917. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  48918. return DirectionalLight;
  48919. }(BABYLON.ShadowLight));
  48920. BABYLON.DirectionalLight = DirectionalLight;
  48921. })(BABYLON || (BABYLON = {}));
  48922. //# sourceMappingURL=babylon.directionalLight.js.map
  48923. var BABYLON;
  48924. (function (BABYLON) {
  48925. /**
  48926. * A spot light is defined by a position, a direction, an angle, and an exponent.
  48927. * These values define a cone of light starting from the position, emitting toward the direction.
  48928. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  48929. * and the exponent defines the speed of the decay of the light with distance (reach).
  48930. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48931. */
  48932. var SpotLight = /** @class */ (function (_super) {
  48933. __extends(SpotLight, _super);
  48934. /**
  48935. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  48936. * It can cast shadows.
  48937. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48938. * @param name The light friendly name
  48939. * @param position The position of the spot light in the scene
  48940. * @param direction The direction of the light in the scene
  48941. * @param angle The cone angle of the light in Radians
  48942. * @param exponent The light decay speed with the distance from the emission spot
  48943. * @param scene The scene the lights belongs to
  48944. */
  48945. function SpotLight(name, position, direction, angle, exponent, scene) {
  48946. var _this = _super.call(this, name, scene) || this;
  48947. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  48948. _this._projectionTextureLightNear = 1e-6;
  48949. _this._projectionTextureLightFar = 1000.0;
  48950. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  48951. _this._projectionTextureViewLightDirty = true;
  48952. _this._projectionTextureProjectionLightDirty = true;
  48953. _this._projectionTextureDirty = true;
  48954. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  48955. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  48956. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  48957. _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);
  48958. _this.position = position;
  48959. _this.direction = direction;
  48960. _this.angle = angle;
  48961. _this.exponent = exponent;
  48962. return _this;
  48963. }
  48964. Object.defineProperty(SpotLight.prototype, "angle", {
  48965. /**
  48966. * Gets the cone angle of the spot light in Radians.
  48967. */
  48968. get: function () {
  48969. return this._angle;
  48970. },
  48971. /**
  48972. * Sets the cone angle of the spot light in Radians.
  48973. */
  48974. set: function (value) {
  48975. this._angle = value;
  48976. this._projectionTextureProjectionLightDirty = true;
  48977. this.forceProjectionMatrixCompute();
  48978. },
  48979. enumerable: true,
  48980. configurable: true
  48981. });
  48982. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  48983. /**
  48984. * Allows scaling the angle of the light for shadow generation only.
  48985. */
  48986. get: function () {
  48987. return this._shadowAngleScale;
  48988. },
  48989. /**
  48990. * Allows scaling the angle of the light for shadow generation only.
  48991. */
  48992. set: function (value) {
  48993. this._shadowAngleScale = value;
  48994. this.forceProjectionMatrixCompute();
  48995. },
  48996. enumerable: true,
  48997. configurable: true
  48998. });
  48999. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49000. /**
  49001. * Allows reading the projecton texture
  49002. */
  49003. get: function () {
  49004. return this._projectionTextureMatrix;
  49005. },
  49006. enumerable: true,
  49007. configurable: true
  49008. });
  49009. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49010. /**
  49011. * Gets the near clip of the Spotlight for texture projection.
  49012. */
  49013. get: function () {
  49014. return this._projectionTextureLightNear;
  49015. },
  49016. /**
  49017. * Sets the near clip of the Spotlight for texture projection.
  49018. */
  49019. set: function (value) {
  49020. this._projectionTextureLightNear = value;
  49021. this._projectionTextureProjectionLightDirty = true;
  49022. },
  49023. enumerable: true,
  49024. configurable: true
  49025. });
  49026. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49027. /**
  49028. * Gets the far clip of the Spotlight for texture projection.
  49029. */
  49030. get: function () {
  49031. return this._projectionTextureLightFar;
  49032. },
  49033. /**
  49034. * Sets the far clip of the Spotlight for texture projection.
  49035. */
  49036. set: function (value) {
  49037. this._projectionTextureLightFar = value;
  49038. this._projectionTextureProjectionLightDirty = true;
  49039. },
  49040. enumerable: true,
  49041. configurable: true
  49042. });
  49043. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49044. /**
  49045. * Gets the Up vector of the Spotlight for texture projection.
  49046. */
  49047. get: function () {
  49048. return this._projectionTextureUpDirection;
  49049. },
  49050. /**
  49051. * Sets the Up vector of the Spotlight for texture projection.
  49052. */
  49053. set: function (value) {
  49054. this._projectionTextureUpDirection = value;
  49055. this._projectionTextureProjectionLightDirty = true;
  49056. },
  49057. enumerable: true,
  49058. configurable: true
  49059. });
  49060. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49061. /**
  49062. * Gets the projection texture of the light.
  49063. */
  49064. get: function () {
  49065. return this._projectionTexture;
  49066. },
  49067. /**
  49068. * Sets the projection texture of the light.
  49069. */
  49070. set: function (value) {
  49071. this._projectionTexture = value;
  49072. this._projectionTextureDirty = true;
  49073. },
  49074. enumerable: true,
  49075. configurable: true
  49076. });
  49077. /**
  49078. * Returns the string "SpotLight".
  49079. * @returns the class name
  49080. */
  49081. SpotLight.prototype.getClassName = function () {
  49082. return "SpotLight";
  49083. };
  49084. /**
  49085. * Returns the integer 2.
  49086. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49087. */
  49088. SpotLight.prototype.getTypeID = function () {
  49089. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49090. };
  49091. /**
  49092. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49093. */
  49094. SpotLight.prototype._setDirection = function (value) {
  49095. _super.prototype._setDirection.call(this, value);
  49096. this._projectionTextureViewLightDirty = true;
  49097. };
  49098. /**
  49099. * Overrides the position setter to recompute the projection texture view light Matrix.
  49100. */
  49101. SpotLight.prototype._setPosition = function (value) {
  49102. _super.prototype._setPosition.call(this, value);
  49103. this._projectionTextureViewLightDirty = true;
  49104. };
  49105. /**
  49106. * 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.
  49107. * Returns the SpotLight.
  49108. */
  49109. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49110. var activeCamera = this.getScene().activeCamera;
  49111. if (!activeCamera) {
  49112. return;
  49113. }
  49114. this._shadowAngleScale = this._shadowAngleScale || 1;
  49115. var angle = this._shadowAngleScale * this._angle;
  49116. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49117. };
  49118. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49119. this._projectionTextureViewLightDirty = false;
  49120. this._projectionTextureDirty = true;
  49121. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49122. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49123. };
  49124. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49125. this._projectionTextureProjectionLightDirty = false;
  49126. this._projectionTextureDirty = true;
  49127. var light_far = this.projectionTextureLightFar;
  49128. var light_near = this.projectionTextureLightNear;
  49129. var P = light_far / (light_far - light_near);
  49130. var Q = -P * light_near;
  49131. var S = 1.0 / Math.tan(this._angle / 2.0);
  49132. var A = 1.0;
  49133. 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);
  49134. };
  49135. /**
  49136. * Main function for light texture projection matrix computing.
  49137. */
  49138. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49139. this._projectionTextureDirty = false;
  49140. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49141. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49142. };
  49143. SpotLight.prototype._buildUniformLayout = function () {
  49144. this._uniformBuffer.addUniform("vLightData", 4);
  49145. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49146. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49147. this._uniformBuffer.addUniform("vLightDirection", 3);
  49148. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49149. this._uniformBuffer.addUniform("depthValues", 2);
  49150. this._uniformBuffer.create();
  49151. };
  49152. /**
  49153. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49154. * @param effect The effect to update
  49155. * @param lightIndex The index of the light in the effect to update
  49156. * @returns The spot light
  49157. */
  49158. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49159. var normalizeDirection;
  49160. if (this.computeTransformedInformation()) {
  49161. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49162. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49163. }
  49164. else {
  49165. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49166. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49167. }
  49168. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49169. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49170. if (this._projectionTextureViewLightDirty) {
  49171. this._computeProjectionTextureViewLightMatrix();
  49172. }
  49173. if (this._projectionTextureProjectionLightDirty) {
  49174. this._computeProjectionTextureProjectionLightMatrix();
  49175. }
  49176. if (this._projectionTextureDirty) {
  49177. this._computeProjectionTextureMatrix();
  49178. }
  49179. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49180. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49181. }
  49182. return this;
  49183. };
  49184. /**
  49185. * Disposes the light and the associated resources.
  49186. */
  49187. SpotLight.prototype.dispose = function () {
  49188. _super.prototype.dispose.call(this);
  49189. if (this._projectionTexture) {
  49190. this._projectionTexture.dispose();
  49191. }
  49192. };
  49193. __decorate([
  49194. BABYLON.serialize()
  49195. ], SpotLight.prototype, "angle", null);
  49196. __decorate([
  49197. BABYLON.serialize()
  49198. ], SpotLight.prototype, "shadowAngleScale", null);
  49199. __decorate([
  49200. BABYLON.serialize()
  49201. ], SpotLight.prototype, "exponent", void 0);
  49202. __decorate([
  49203. BABYLON.serialize()
  49204. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49205. __decorate([
  49206. BABYLON.serialize()
  49207. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49208. __decorate([
  49209. BABYLON.serialize()
  49210. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49211. __decorate([
  49212. BABYLON.serializeAsTexture("projectedLightTexture")
  49213. ], SpotLight.prototype, "_projectionTexture", void 0);
  49214. return SpotLight;
  49215. }(BABYLON.ShadowLight));
  49216. BABYLON.SpotLight = SpotLight;
  49217. })(BABYLON || (BABYLON = {}));
  49218. //# sourceMappingURL=babylon.spotLight.js.map
  49219. var BABYLON;
  49220. (function (BABYLON) {
  49221. /**
  49222. * Class used to override all child animations of a given target
  49223. */
  49224. var AnimationPropertiesOverride = /** @class */ (function () {
  49225. function AnimationPropertiesOverride() {
  49226. /**
  49227. * Gets or sets a value indicating if animation blending must be used
  49228. */
  49229. this.enableBlending = false;
  49230. /**
  49231. * Gets or sets the blending speed to use when enableBlending is true
  49232. */
  49233. this.blendingSpeed = 0.01;
  49234. /**
  49235. * Gets or sets the default loop mode to use
  49236. */
  49237. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49238. }
  49239. return AnimationPropertiesOverride;
  49240. }());
  49241. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49242. })(BABYLON || (BABYLON = {}));
  49243. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49244. var BABYLON;
  49245. (function (BABYLON) {
  49246. /**
  49247. * Represents the range of an animation
  49248. */
  49249. var AnimationRange = /** @class */ (function () {
  49250. /**
  49251. * Initializes the range of an animation
  49252. * @param name The name of the animation range
  49253. * @param from The starting frame of the animation
  49254. * @param to The ending frame of the animation
  49255. */
  49256. function AnimationRange(
  49257. /**The name of the animation range**/
  49258. name,
  49259. /**The starting frame of the animation */
  49260. from,
  49261. /**The ending frame of the animation*/
  49262. to) {
  49263. this.name = name;
  49264. this.from = from;
  49265. this.to = to;
  49266. }
  49267. /**
  49268. * Makes a copy of the animation range
  49269. * @returns A copy of the animation range
  49270. */
  49271. AnimationRange.prototype.clone = function () {
  49272. return new AnimationRange(this.name, this.from, this.to);
  49273. };
  49274. return AnimationRange;
  49275. }());
  49276. BABYLON.AnimationRange = AnimationRange;
  49277. /**
  49278. * Composed of a frame, and an action function
  49279. */
  49280. var AnimationEvent = /** @class */ (function () {
  49281. /**
  49282. * Initializes the animation event
  49283. * @param frame The frame for which the event is triggered
  49284. * @param action The event to perform when triggered
  49285. * @param onlyOnce Specifies if the event should be triggered only once
  49286. */
  49287. function AnimationEvent(
  49288. /** The frame for which the event is triggered **/
  49289. frame,
  49290. /** The event to perform when triggered **/
  49291. action,
  49292. /** Specifies if the event should be triggered only once**/
  49293. onlyOnce) {
  49294. this.frame = frame;
  49295. this.action = action;
  49296. this.onlyOnce = onlyOnce;
  49297. /**
  49298. * Specifies if the animation event is done
  49299. */
  49300. this.isDone = false;
  49301. }
  49302. /** @hidden */
  49303. AnimationEvent.prototype._clone = function () {
  49304. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49305. };
  49306. return AnimationEvent;
  49307. }());
  49308. BABYLON.AnimationEvent = AnimationEvent;
  49309. /**
  49310. * A cursor which tracks a point on a path
  49311. */
  49312. var PathCursor = /** @class */ (function () {
  49313. /**
  49314. * Initializes the path cursor
  49315. * @param path The path to track
  49316. */
  49317. function PathCursor(path) {
  49318. this.path = path;
  49319. /**
  49320. * Stores path cursor callbacks for when an onchange event is triggered
  49321. */
  49322. this._onchange = new Array();
  49323. /**
  49324. * The value of the path cursor
  49325. */
  49326. this.value = 0;
  49327. /**
  49328. * The animation array of the path cursor
  49329. */
  49330. this.animations = new Array();
  49331. }
  49332. /**
  49333. * Gets the cursor point on the path
  49334. * @returns A point on the path cursor at the cursor location
  49335. */
  49336. PathCursor.prototype.getPoint = function () {
  49337. var point = this.path.getPointAtLengthPosition(this.value);
  49338. return new BABYLON.Vector3(point.x, 0, point.y);
  49339. };
  49340. /**
  49341. * Moves the cursor ahead by the step amount
  49342. * @param step The amount to move the cursor forward
  49343. * @returns This path cursor
  49344. */
  49345. PathCursor.prototype.moveAhead = function (step) {
  49346. if (step === void 0) { step = 0.002; }
  49347. this.move(step);
  49348. return this;
  49349. };
  49350. /**
  49351. * Moves the cursor behind by the step amount
  49352. * @param step The amount to move the cursor back
  49353. * @returns This path cursor
  49354. */
  49355. PathCursor.prototype.moveBack = function (step) {
  49356. if (step === void 0) { step = 0.002; }
  49357. this.move(-step);
  49358. return this;
  49359. };
  49360. /**
  49361. * Moves the cursor by the step amount
  49362. * If the step amount is greater than one, an exception is thrown
  49363. * @param step The amount to move the cursor
  49364. * @returns This path cursor
  49365. */
  49366. PathCursor.prototype.move = function (step) {
  49367. if (Math.abs(step) > 1) {
  49368. throw "step size should be less than 1.";
  49369. }
  49370. this.value += step;
  49371. this.ensureLimits();
  49372. this.raiseOnChange();
  49373. return this;
  49374. };
  49375. /**
  49376. * Ensures that the value is limited between zero and one
  49377. * @returns This path cursor
  49378. */
  49379. PathCursor.prototype.ensureLimits = function () {
  49380. while (this.value > 1) {
  49381. this.value -= 1;
  49382. }
  49383. while (this.value < 0) {
  49384. this.value += 1;
  49385. }
  49386. return this;
  49387. };
  49388. /**
  49389. * Runs onchange callbacks on change (used by the animation engine)
  49390. * @returns This path cursor
  49391. */
  49392. PathCursor.prototype.raiseOnChange = function () {
  49393. var _this = this;
  49394. this._onchange.forEach(function (f) { return f(_this); });
  49395. return this;
  49396. };
  49397. /**
  49398. * Executes a function on change
  49399. * @param f A path cursor onchange callback
  49400. * @returns This path cursor
  49401. */
  49402. PathCursor.prototype.onchange = function (f) {
  49403. this._onchange.push(f);
  49404. return this;
  49405. };
  49406. return PathCursor;
  49407. }());
  49408. BABYLON.PathCursor = PathCursor;
  49409. /**
  49410. * Enum for the animation key frame interpolation type
  49411. */
  49412. var AnimationKeyInterpolation;
  49413. (function (AnimationKeyInterpolation) {
  49414. /**
  49415. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49416. */
  49417. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49418. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49419. /**
  49420. * Class used to store any kind of animation
  49421. */
  49422. var Animation = /** @class */ (function () {
  49423. /**
  49424. * Initializes the animation
  49425. * @param name Name of the animation
  49426. * @param targetProperty Property to animate
  49427. * @param framePerSecond The frames per second of the animation
  49428. * @param dataType The data type of the animation
  49429. * @param loopMode The loop mode of the animation
  49430. * @param enableBlendings Specifies if blending should be enabled
  49431. */
  49432. function Animation(
  49433. /**Name of the animation */
  49434. name,
  49435. /**Property to animate */
  49436. targetProperty,
  49437. /**The frames per second of the animation */
  49438. framePerSecond,
  49439. /**The data type of the animation */
  49440. dataType,
  49441. /**The loop mode of the animation */
  49442. loopMode,
  49443. /**Specifies if blending should be enabled */
  49444. enableBlending) {
  49445. this.name = name;
  49446. this.targetProperty = targetProperty;
  49447. this.framePerSecond = framePerSecond;
  49448. this.dataType = dataType;
  49449. this.loopMode = loopMode;
  49450. this.enableBlending = enableBlending;
  49451. /**
  49452. * @hidden Internal use only
  49453. */
  49454. this._runtimeAnimations = new Array();
  49455. /**
  49456. * The set of event that will be linked to this animation
  49457. */
  49458. this._events = new Array();
  49459. /**
  49460. * Stores the blending speed of the animation
  49461. */
  49462. this.blendingSpeed = 0.01;
  49463. /**
  49464. * Stores the animation ranges for the animation
  49465. */
  49466. this._ranges = {};
  49467. this.targetPropertyPath = targetProperty.split(".");
  49468. this.dataType = dataType;
  49469. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49470. }
  49471. /**
  49472. * @hidden Internal use
  49473. */
  49474. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49475. var dataType = undefined;
  49476. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49477. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49478. }
  49479. else if (from instanceof BABYLON.Quaternion) {
  49480. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49481. }
  49482. else if (from instanceof BABYLON.Vector3) {
  49483. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49484. }
  49485. else if (from instanceof BABYLON.Vector2) {
  49486. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49487. }
  49488. else if (from instanceof BABYLON.Color3) {
  49489. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49490. }
  49491. else if (from instanceof BABYLON.Size) {
  49492. dataType = Animation.ANIMATIONTYPE_SIZE;
  49493. }
  49494. if (dataType == undefined) {
  49495. return null;
  49496. }
  49497. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49498. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49499. animation.setKeys(keys);
  49500. if (easingFunction !== undefined) {
  49501. animation.setEasingFunction(easingFunction);
  49502. }
  49503. return animation;
  49504. };
  49505. /**
  49506. * Sets up an animation
  49507. * @param property The property to animate
  49508. * @param animationType The animation type to apply
  49509. * @param framePerSecond The frames per second of the animation
  49510. * @param easingFunction The easing function used in the animation
  49511. * @returns The created animation
  49512. */
  49513. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49514. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49515. animation.setEasingFunction(easingFunction);
  49516. return animation;
  49517. };
  49518. /**
  49519. * Create and start an animation on a node
  49520. * @param name defines the name of the global animation that will be run on all nodes
  49521. * @param node defines the root node where the animation will take place
  49522. * @param targetProperty defines property to animate
  49523. * @param framePerSecond defines the number of frame per second yo use
  49524. * @param totalFrame defines the number of frames in total
  49525. * @param from defines the initial value
  49526. * @param to defines the final value
  49527. * @param loopMode defines which loop mode you want to use (off by default)
  49528. * @param easingFunction defines the easing function to use (linear by default)
  49529. * @param onAnimationEnd defines the callback to call when animation end
  49530. * @returns the animatable created for this animation
  49531. */
  49532. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49533. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49534. if (!animation) {
  49535. return null;
  49536. }
  49537. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49538. };
  49539. /**
  49540. * Create and start an animation on a node and its descendants
  49541. * @param name defines the name of the global animation that will be run on all nodes
  49542. * @param node defines the root node where the animation will take place
  49543. * @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
  49544. * @param targetProperty defines property to animate
  49545. * @param framePerSecond defines the number of frame per second to use
  49546. * @param totalFrame defines the number of frames in total
  49547. * @param from defines the initial value
  49548. * @param to defines the final value
  49549. * @param loopMode defines which loop mode you want to use (off by default)
  49550. * @param easingFunction defines the easing function to use (linear by default)
  49551. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49552. * @returns the list of animatables created for all nodes
  49553. * @example https://www.babylonjs-playground.com/#MH0VLI
  49554. */
  49555. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49556. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49557. if (!animation) {
  49558. return null;
  49559. }
  49560. var scene = node.getScene();
  49561. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49562. };
  49563. /**
  49564. * Creates a new animation, merges it with the existing animations and starts it
  49565. * @param name Name of the animation
  49566. * @param node Node which contains the scene that begins the animations
  49567. * @param targetProperty Specifies which property to animate
  49568. * @param framePerSecond The frames per second of the animation
  49569. * @param totalFrame The total number of frames
  49570. * @param from The frame at the beginning of the animation
  49571. * @param to The frame at the end of the animation
  49572. * @param loopMode Specifies the loop mode of the animation
  49573. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49574. * @param onAnimationEnd Callback to run once the animation is complete
  49575. * @returns Nullable animation
  49576. */
  49577. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49578. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49579. if (!animation) {
  49580. return null;
  49581. }
  49582. node.animations.push(animation);
  49583. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49584. };
  49585. /**
  49586. * Transition property of an host to the target Value
  49587. * @param property The property to transition
  49588. * @param targetValue The target Value of the property
  49589. * @param host The object where the property to animate belongs
  49590. * @param scene Scene used to run the animation
  49591. * @param frameRate Framerate (in frame/s) to use
  49592. * @param transition The transition type we want to use
  49593. * @param duration The duration of the animation, in milliseconds
  49594. * @param onAnimationEnd Callback trigger at the end of the animation
  49595. * @returns Nullable animation
  49596. */
  49597. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49598. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49599. if (duration <= 0) {
  49600. host[property] = targetValue;
  49601. if (onAnimationEnd) {
  49602. onAnimationEnd();
  49603. }
  49604. return null;
  49605. }
  49606. var endFrame = frameRate * (duration / 1000);
  49607. transition.setKeys([{
  49608. frame: 0,
  49609. value: host[property].clone ? host[property].clone() : host[property]
  49610. },
  49611. {
  49612. frame: endFrame,
  49613. value: targetValue
  49614. }]);
  49615. if (!host.animations) {
  49616. host.animations = [];
  49617. }
  49618. host.animations.push(transition);
  49619. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49620. animation.onAnimationEnd = onAnimationEnd;
  49621. return animation;
  49622. };
  49623. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49624. /**
  49625. * Return the array of runtime animations currently using this animation
  49626. */
  49627. get: function () {
  49628. return this._runtimeAnimations;
  49629. },
  49630. enumerable: true,
  49631. configurable: true
  49632. });
  49633. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49634. /**
  49635. * Specifies if any of the runtime animations are currently running
  49636. */
  49637. get: function () {
  49638. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49639. var runtimeAnimation = _a[_i];
  49640. if (!runtimeAnimation.isStopped) {
  49641. return true;
  49642. }
  49643. }
  49644. return false;
  49645. },
  49646. enumerable: true,
  49647. configurable: true
  49648. });
  49649. // Methods
  49650. /**
  49651. * Converts the animation to a string
  49652. * @param fullDetails support for multiple levels of logging within scene loading
  49653. * @returns String form of the animation
  49654. */
  49655. Animation.prototype.toString = function (fullDetails) {
  49656. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49657. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49658. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49659. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49660. if (fullDetails) {
  49661. ret += ", Ranges: {";
  49662. var first = true;
  49663. for (var name in this._ranges) {
  49664. if (first) {
  49665. ret += ", ";
  49666. first = false;
  49667. }
  49668. ret += name;
  49669. }
  49670. ret += "}";
  49671. }
  49672. return ret;
  49673. };
  49674. /**
  49675. * Add an event to this animation
  49676. * @param event Event to add
  49677. */
  49678. Animation.prototype.addEvent = function (event) {
  49679. this._events.push(event);
  49680. };
  49681. /**
  49682. * Remove all events found at the given frame
  49683. * @param frame The frame to remove events from
  49684. */
  49685. Animation.prototype.removeEvents = function (frame) {
  49686. for (var index = 0; index < this._events.length; index++) {
  49687. if (this._events[index].frame === frame) {
  49688. this._events.splice(index, 1);
  49689. index--;
  49690. }
  49691. }
  49692. };
  49693. /**
  49694. * Retrieves all the events from the animation
  49695. * @returns Events from the animation
  49696. */
  49697. Animation.prototype.getEvents = function () {
  49698. return this._events;
  49699. };
  49700. /**
  49701. * Creates an animation range
  49702. * @param name Name of the animation range
  49703. * @param from Starting frame of the animation range
  49704. * @param to Ending frame of the animation
  49705. */
  49706. Animation.prototype.createRange = function (name, from, to) {
  49707. // check name not already in use; could happen for bones after serialized
  49708. if (!this._ranges[name]) {
  49709. this._ranges[name] = new AnimationRange(name, from, to);
  49710. }
  49711. };
  49712. /**
  49713. * Deletes an animation range by name
  49714. * @param name Name of the animation range to delete
  49715. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49716. */
  49717. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49718. if (deleteFrames === void 0) { deleteFrames = true; }
  49719. var range = this._ranges[name];
  49720. if (!range) {
  49721. return;
  49722. }
  49723. if (deleteFrames) {
  49724. var from = range.from;
  49725. var to = range.to;
  49726. // this loop MUST go high to low for multiple splices to work
  49727. for (var key = this._keys.length - 1; key >= 0; key--) {
  49728. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49729. this._keys.splice(key, 1);
  49730. }
  49731. }
  49732. }
  49733. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49734. };
  49735. /**
  49736. * Gets the animation range by name, or null if not defined
  49737. * @param name Name of the animation range
  49738. * @returns Nullable animation range
  49739. */
  49740. Animation.prototype.getRange = function (name) {
  49741. return this._ranges[name];
  49742. };
  49743. /**
  49744. * Gets the key frames from the animation
  49745. * @returns The key frames of the animation
  49746. */
  49747. Animation.prototype.getKeys = function () {
  49748. return this._keys;
  49749. };
  49750. /**
  49751. * Gets the highest frame rate of the animation
  49752. * @returns Highest frame rate of the animation
  49753. */
  49754. Animation.prototype.getHighestFrame = function () {
  49755. var ret = 0;
  49756. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49757. if (ret < this._keys[key].frame) {
  49758. ret = this._keys[key].frame;
  49759. }
  49760. }
  49761. return ret;
  49762. };
  49763. /**
  49764. * Gets the easing function of the animation
  49765. * @returns Easing function of the animation
  49766. */
  49767. Animation.prototype.getEasingFunction = function () {
  49768. return this._easingFunction;
  49769. };
  49770. /**
  49771. * Sets the easing function of the animation
  49772. * @param easingFunction A custom mathematical formula for animation
  49773. */
  49774. Animation.prototype.setEasingFunction = function (easingFunction) {
  49775. this._easingFunction = easingFunction;
  49776. };
  49777. /**
  49778. * Interpolates a scalar linearly
  49779. * @param startValue Start value of the animation curve
  49780. * @param endValue End value of the animation curve
  49781. * @param gradient Scalar amount to interpolate
  49782. * @returns Interpolated scalar value
  49783. */
  49784. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49785. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49786. };
  49787. /**
  49788. * Interpolates a scalar cubically
  49789. * @param startValue Start value of the animation curve
  49790. * @param outTangent End tangent of the animation
  49791. * @param endValue End value of the animation curve
  49792. * @param inTangent Start tangent of the animation curve
  49793. * @param gradient Scalar amount to interpolate
  49794. * @returns Interpolated scalar value
  49795. */
  49796. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49797. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49798. };
  49799. /**
  49800. * Interpolates a quaternion using a spherical linear interpolation
  49801. * @param startValue Start value of the animation curve
  49802. * @param endValue End value of the animation curve
  49803. * @param gradient Scalar amount to interpolate
  49804. * @returns Interpolated quaternion value
  49805. */
  49806. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49807. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49808. };
  49809. /**
  49810. * Interpolates a quaternion cubically
  49811. * @param startValue Start value of the animation curve
  49812. * @param outTangent End tangent of the animation curve
  49813. * @param endValue End value of the animation curve
  49814. * @param inTangent Start tangent of the animation curve
  49815. * @param gradient Scalar amount to interpolate
  49816. * @returns Interpolated quaternion value
  49817. */
  49818. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49819. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49820. };
  49821. /**
  49822. * Interpolates a Vector3 linearl
  49823. * @param startValue Start value of the animation curve
  49824. * @param endValue End value of the animation curve
  49825. * @param gradient Scalar amount to interpolate
  49826. * @returns Interpolated scalar value
  49827. */
  49828. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49829. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49830. };
  49831. /**
  49832. * Interpolates a Vector3 cubically
  49833. * @param startValue Start value of the animation curve
  49834. * @param outTangent End tangent of the animation
  49835. * @param endValue End value of the animation curve
  49836. * @param inTangent Start tangent of the animation curve
  49837. * @param gradient Scalar amount to interpolate
  49838. * @returns InterpolatedVector3 value
  49839. */
  49840. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49841. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49842. };
  49843. /**
  49844. * Interpolates a Vector2 linearly
  49845. * @param startValue Start value of the animation curve
  49846. * @param endValue End value of the animation curve
  49847. * @param gradient Scalar amount to interpolate
  49848. * @returns Interpolated Vector2 value
  49849. */
  49850. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49851. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49852. };
  49853. /**
  49854. * Interpolates a Vector2 cubically
  49855. * @param startValue Start value of the animation curve
  49856. * @param outTangent End tangent of the animation
  49857. * @param endValue End value of the animation curve
  49858. * @param inTangent Start tangent of the animation curve
  49859. * @param gradient Scalar amount to interpolate
  49860. * @returns Interpolated Vector2 value
  49861. */
  49862. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49863. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49864. };
  49865. /**
  49866. * Interpolates a size linearly
  49867. * @param startValue Start value of the animation curve
  49868. * @param endValue End value of the animation curve
  49869. * @param gradient Scalar amount to interpolate
  49870. * @returns Interpolated Size value
  49871. */
  49872. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49873. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49874. };
  49875. /**
  49876. * Interpolates a Color3 linearly
  49877. * @param startValue Start value of the animation curve
  49878. * @param endValue End value of the animation curve
  49879. * @param gradient Scalar amount to interpolate
  49880. * @returns Interpolated Color3 value
  49881. */
  49882. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49883. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49884. };
  49885. /**
  49886. * @hidden Internal use only
  49887. */
  49888. Animation.prototype._getKeyValue = function (value) {
  49889. if (typeof value === "function") {
  49890. return value();
  49891. }
  49892. return value;
  49893. };
  49894. /**
  49895. * @hidden Internal use only
  49896. */
  49897. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49898. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49899. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49900. }
  49901. var keys = this.getKeys();
  49902. // Try to get a hash to find the right key
  49903. 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));
  49904. if (keys[startKeyIndex].frame >= currentFrame) {
  49905. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49906. startKeyIndex--;
  49907. }
  49908. }
  49909. for (var key = startKeyIndex; key < keys.length; key++) {
  49910. var endKey = keys[key + 1];
  49911. if (endKey.frame >= currentFrame) {
  49912. var startKey = keys[key];
  49913. var startValue = this._getKeyValue(startKey.value);
  49914. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49915. return startValue;
  49916. }
  49917. var endValue = this._getKeyValue(endKey.value);
  49918. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  49919. var frameDelta = endKey.frame - startKey.frame;
  49920. // gradient : percent of currentFrame between the frame inf and the frame sup
  49921. var gradient = (currentFrame - startKey.frame) / frameDelta;
  49922. // check for easingFunction and correction of gradient
  49923. var easingFunction = this.getEasingFunction();
  49924. if (easingFunction != null) {
  49925. gradient = easingFunction.ease(gradient);
  49926. }
  49927. switch (this.dataType) {
  49928. // Float
  49929. case Animation.ANIMATIONTYPE_FLOAT:
  49930. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  49931. switch (loopMode) {
  49932. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49933. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49934. return floatValue;
  49935. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49936. return offsetValue * repeatCount + floatValue;
  49937. }
  49938. break;
  49939. // Quaternion
  49940. case Animation.ANIMATIONTYPE_QUATERNION:
  49941. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  49942. switch (loopMode) {
  49943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49945. return quatValue;
  49946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49947. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  49948. }
  49949. return quatValue;
  49950. // Vector3
  49951. case Animation.ANIMATIONTYPE_VECTOR3:
  49952. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  49953. switch (loopMode) {
  49954. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49955. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49956. return vec3Value;
  49957. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49958. return vec3Value.add(offsetValue.scale(repeatCount));
  49959. }
  49960. // Vector2
  49961. case Animation.ANIMATIONTYPE_VECTOR2:
  49962. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  49963. switch (loopMode) {
  49964. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49965. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49966. return vec2Value;
  49967. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49968. return vec2Value.add(offsetValue.scale(repeatCount));
  49969. }
  49970. // Size
  49971. case Animation.ANIMATIONTYPE_SIZE:
  49972. switch (loopMode) {
  49973. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49974. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49975. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  49976. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49977. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49978. }
  49979. // Color3
  49980. case Animation.ANIMATIONTYPE_COLOR3:
  49981. switch (loopMode) {
  49982. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49983. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49984. return this.color3InterpolateFunction(startValue, endValue, gradient);
  49985. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49986. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  49987. }
  49988. // Matrix
  49989. case Animation.ANIMATIONTYPE_MATRIX:
  49990. switch (loopMode) {
  49991. case Animation.ANIMATIONLOOPMODE_CYCLE:
  49992. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  49993. if (Animation.AllowMatricesInterpolation) {
  49994. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  49995. }
  49996. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  49997. return startValue;
  49998. }
  49999. default:
  50000. break;
  50001. }
  50002. break;
  50003. }
  50004. }
  50005. return this._getKeyValue(keys[keys.length - 1].value);
  50006. };
  50007. /**
  50008. * Defines the function to use to interpolate matrices
  50009. * @param startValue defines the start matrix
  50010. * @param endValue defines the end matrix
  50011. * @param gradient defines the gradient between both matrices
  50012. * @param result defines an optional target matrix where to store the interpolation
  50013. * @returns the interpolated matrix
  50014. */
  50015. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50016. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50017. if (result) {
  50018. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50019. return result;
  50020. }
  50021. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50022. }
  50023. if (result) {
  50024. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50025. return result;
  50026. }
  50027. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50028. };
  50029. /**
  50030. * Makes a copy of the animation
  50031. * @returns Cloned animation
  50032. */
  50033. Animation.prototype.clone = function () {
  50034. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50035. clone.enableBlending = this.enableBlending;
  50036. clone.blendingSpeed = this.blendingSpeed;
  50037. if (this._keys) {
  50038. clone.setKeys(this._keys);
  50039. }
  50040. if (this._ranges) {
  50041. clone._ranges = {};
  50042. for (var name in this._ranges) {
  50043. var range = this._ranges[name];
  50044. if (!range) {
  50045. continue;
  50046. }
  50047. clone._ranges[name] = range.clone();
  50048. }
  50049. }
  50050. return clone;
  50051. };
  50052. /**
  50053. * Sets the key frames of the animation
  50054. * @param values The animation key frames to set
  50055. */
  50056. Animation.prototype.setKeys = function (values) {
  50057. this._keys = values.slice(0);
  50058. };
  50059. /**
  50060. * Serializes the animation to an object
  50061. * @returns Serialized object
  50062. */
  50063. Animation.prototype.serialize = function () {
  50064. var serializationObject = {};
  50065. serializationObject.name = this.name;
  50066. serializationObject.property = this.targetProperty;
  50067. serializationObject.framePerSecond = this.framePerSecond;
  50068. serializationObject.dataType = this.dataType;
  50069. serializationObject.loopBehavior = this.loopMode;
  50070. serializationObject.enableBlending = this.enableBlending;
  50071. serializationObject.blendingSpeed = this.blendingSpeed;
  50072. var dataType = this.dataType;
  50073. serializationObject.keys = [];
  50074. var keys = this.getKeys();
  50075. for (var index = 0; index < keys.length; index++) {
  50076. var animationKey = keys[index];
  50077. var key = {};
  50078. key.frame = animationKey.frame;
  50079. switch (dataType) {
  50080. case Animation.ANIMATIONTYPE_FLOAT:
  50081. key.values = [animationKey.value];
  50082. break;
  50083. case Animation.ANIMATIONTYPE_QUATERNION:
  50084. case Animation.ANIMATIONTYPE_MATRIX:
  50085. case Animation.ANIMATIONTYPE_VECTOR3:
  50086. case Animation.ANIMATIONTYPE_COLOR3:
  50087. key.values = animationKey.value.asArray();
  50088. break;
  50089. }
  50090. serializationObject.keys.push(key);
  50091. }
  50092. serializationObject.ranges = [];
  50093. for (var name in this._ranges) {
  50094. var source = this._ranges[name];
  50095. if (!source) {
  50096. continue;
  50097. }
  50098. var range = {};
  50099. range.name = name;
  50100. range.from = source.from;
  50101. range.to = source.to;
  50102. serializationObject.ranges.push(range);
  50103. }
  50104. return serializationObject;
  50105. };
  50106. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50107. /**
  50108. * Get the float animation type
  50109. */
  50110. get: function () {
  50111. return Animation._ANIMATIONTYPE_FLOAT;
  50112. },
  50113. enumerable: true,
  50114. configurable: true
  50115. });
  50116. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50117. /**
  50118. * Get the Vector3 animation type
  50119. */
  50120. get: function () {
  50121. return Animation._ANIMATIONTYPE_VECTOR3;
  50122. },
  50123. enumerable: true,
  50124. configurable: true
  50125. });
  50126. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50127. /**
  50128. * Get the Vectpr2 animation type
  50129. */
  50130. get: function () {
  50131. return Animation._ANIMATIONTYPE_VECTOR2;
  50132. },
  50133. enumerable: true,
  50134. configurable: true
  50135. });
  50136. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50137. /**
  50138. * Get the Size animation type
  50139. */
  50140. get: function () {
  50141. return Animation._ANIMATIONTYPE_SIZE;
  50142. },
  50143. enumerable: true,
  50144. configurable: true
  50145. });
  50146. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50147. /**
  50148. * Get the Quaternion animation type
  50149. */
  50150. get: function () {
  50151. return Animation._ANIMATIONTYPE_QUATERNION;
  50152. },
  50153. enumerable: true,
  50154. configurable: true
  50155. });
  50156. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50157. /**
  50158. * Get the Matrix animation type
  50159. */
  50160. get: function () {
  50161. return Animation._ANIMATIONTYPE_MATRIX;
  50162. },
  50163. enumerable: true,
  50164. configurable: true
  50165. });
  50166. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50167. /**
  50168. * Get the Color3 animation type
  50169. */
  50170. get: function () {
  50171. return Animation._ANIMATIONTYPE_COLOR3;
  50172. },
  50173. enumerable: true,
  50174. configurable: true
  50175. });
  50176. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50177. /**
  50178. * Get the Relative Loop Mode
  50179. */
  50180. get: function () {
  50181. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50182. },
  50183. enumerable: true,
  50184. configurable: true
  50185. });
  50186. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50187. /**
  50188. * Get the Cycle Loop Mode
  50189. */
  50190. get: function () {
  50191. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50192. },
  50193. enumerable: true,
  50194. configurable: true
  50195. });
  50196. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50197. /**
  50198. * Get the Constant Loop Mode
  50199. */
  50200. get: function () {
  50201. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50202. },
  50203. enumerable: true,
  50204. configurable: true
  50205. });
  50206. /** @hidden */
  50207. Animation._UniversalLerp = function (left, right, amount) {
  50208. var constructor = left.constructor;
  50209. if (constructor.Lerp) { // Lerp supported
  50210. return constructor.Lerp(left, right, amount);
  50211. }
  50212. else if (constructor.Slerp) { // Slerp supported
  50213. return constructor.Slerp(left, right, amount);
  50214. }
  50215. else if (left.toFixed) { // Number
  50216. return left * (1.0 - amount) + amount * right;
  50217. }
  50218. else { // Blending not supported
  50219. return right;
  50220. }
  50221. };
  50222. /**
  50223. * Parses an animation object and creates an animation
  50224. * @param parsedAnimation Parsed animation object
  50225. * @returns Animation object
  50226. */
  50227. Animation.Parse = function (parsedAnimation) {
  50228. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50229. var dataType = parsedAnimation.dataType;
  50230. var keys = [];
  50231. var data;
  50232. var index;
  50233. if (parsedAnimation.enableBlending) {
  50234. animation.enableBlending = parsedAnimation.enableBlending;
  50235. }
  50236. if (parsedAnimation.blendingSpeed) {
  50237. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50238. }
  50239. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50240. var key = parsedAnimation.keys[index];
  50241. var inTangent;
  50242. var outTangent;
  50243. switch (dataType) {
  50244. case Animation.ANIMATIONTYPE_FLOAT:
  50245. data = key.values[0];
  50246. if (key.values.length >= 1) {
  50247. inTangent = key.values[1];
  50248. }
  50249. if (key.values.length >= 2) {
  50250. outTangent = key.values[2];
  50251. }
  50252. break;
  50253. case Animation.ANIMATIONTYPE_QUATERNION:
  50254. data = BABYLON.Quaternion.FromArray(key.values);
  50255. if (key.values.length >= 8) {
  50256. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50257. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50258. inTangent = _inTangent;
  50259. }
  50260. }
  50261. if (key.values.length >= 12) {
  50262. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50263. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50264. outTangent = _outTangent;
  50265. }
  50266. }
  50267. break;
  50268. case Animation.ANIMATIONTYPE_MATRIX:
  50269. data = BABYLON.Matrix.FromArray(key.values);
  50270. break;
  50271. case Animation.ANIMATIONTYPE_COLOR3:
  50272. data = BABYLON.Color3.FromArray(key.values);
  50273. break;
  50274. case Animation.ANIMATIONTYPE_VECTOR3:
  50275. default:
  50276. data = BABYLON.Vector3.FromArray(key.values);
  50277. break;
  50278. }
  50279. var keyData = {};
  50280. keyData.frame = key.frame;
  50281. keyData.value = data;
  50282. if (inTangent != undefined) {
  50283. keyData.inTangent = inTangent;
  50284. }
  50285. if (outTangent != undefined) {
  50286. keyData.outTangent = outTangent;
  50287. }
  50288. keys.push(keyData);
  50289. }
  50290. animation.setKeys(keys);
  50291. if (parsedAnimation.ranges) {
  50292. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50293. data = parsedAnimation.ranges[index];
  50294. animation.createRange(data.name, data.from, data.to);
  50295. }
  50296. }
  50297. return animation;
  50298. };
  50299. /**
  50300. * Appends the serialized animations from the source animations
  50301. * @param source Source containing the animations
  50302. * @param destination Target to store the animations
  50303. */
  50304. Animation.AppendSerializedAnimations = function (source, destination) {
  50305. if (source.animations) {
  50306. destination.animations = [];
  50307. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50308. var animation = source.animations[animationIndex];
  50309. destination.animations.push(animation.serialize());
  50310. }
  50311. }
  50312. };
  50313. /**
  50314. * Use matrix interpolation instead of using direct key value when animating matrices
  50315. */
  50316. Animation.AllowMatricesInterpolation = false;
  50317. /**
  50318. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50319. */
  50320. Animation.AllowMatrixDecomposeForInterpolation = true;
  50321. // Statics
  50322. /**
  50323. * Float animation type
  50324. */
  50325. Animation._ANIMATIONTYPE_FLOAT = 0;
  50326. /**
  50327. * Vector3 animation type
  50328. */
  50329. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50330. /**
  50331. * Quaternion animation type
  50332. */
  50333. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50334. /**
  50335. * Matrix animation type
  50336. */
  50337. Animation._ANIMATIONTYPE_MATRIX = 3;
  50338. /**
  50339. * Color3 animation type
  50340. */
  50341. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50342. /**
  50343. * Vector2 animation type
  50344. */
  50345. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50346. /**
  50347. * Size animation type
  50348. */
  50349. Animation._ANIMATIONTYPE_SIZE = 6;
  50350. /**
  50351. * Relative Loop Mode
  50352. */
  50353. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50354. /**
  50355. * Cycle Loop Mode
  50356. */
  50357. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50358. /**
  50359. * Constant Loop Mode
  50360. */
  50361. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50362. return Animation;
  50363. }());
  50364. BABYLON.Animation = Animation;
  50365. })(BABYLON || (BABYLON = {}));
  50366. //# sourceMappingURL=babylon.animation.js.map
  50367. var BABYLON;
  50368. (function (BABYLON) {
  50369. /**
  50370. * This class defines the direct association between an animation and a target
  50371. */
  50372. var TargetedAnimation = /** @class */ (function () {
  50373. function TargetedAnimation() {
  50374. }
  50375. return TargetedAnimation;
  50376. }());
  50377. BABYLON.TargetedAnimation = TargetedAnimation;
  50378. /**
  50379. * Use this class to create coordinated animations on multiple targets
  50380. */
  50381. var AnimationGroup = /** @class */ (function () {
  50382. function AnimationGroup(name, scene) {
  50383. if (scene === void 0) { scene = null; }
  50384. this.name = name;
  50385. this._targetedAnimations = new Array();
  50386. this._animatables = new Array();
  50387. this._from = Number.MAX_VALUE;
  50388. this._to = -Number.MAX_VALUE;
  50389. this._speedRatio = 1;
  50390. this.onAnimationEndObservable = new BABYLON.Observable();
  50391. /**
  50392. * This observable will notify when all animations have ended.
  50393. */
  50394. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50395. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50396. this._scene.animationGroups.push(this);
  50397. }
  50398. Object.defineProperty(AnimationGroup.prototype, "from", {
  50399. /**
  50400. * Gets the first frame
  50401. */
  50402. get: function () {
  50403. return this._from;
  50404. },
  50405. enumerable: true,
  50406. configurable: true
  50407. });
  50408. Object.defineProperty(AnimationGroup.prototype, "to", {
  50409. /**
  50410. * Gets the last frame
  50411. */
  50412. get: function () {
  50413. return this._to;
  50414. },
  50415. enumerable: true,
  50416. configurable: true
  50417. });
  50418. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50419. /**
  50420. * Define if the animations are started
  50421. */
  50422. get: function () {
  50423. return this._isStarted;
  50424. },
  50425. enumerable: true,
  50426. configurable: true
  50427. });
  50428. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50429. /**
  50430. * Gets or sets the speed ratio to use for all animations
  50431. */
  50432. get: function () {
  50433. return this._speedRatio;
  50434. },
  50435. /**
  50436. * Gets or sets the speed ratio to use for all animations
  50437. */
  50438. set: function (value) {
  50439. if (this._speedRatio === value) {
  50440. return;
  50441. }
  50442. this._speedRatio = value;
  50443. for (var index = 0; index < this._animatables.length; index++) {
  50444. var animatable = this._animatables[index];
  50445. animatable.speedRatio = this._speedRatio;
  50446. }
  50447. },
  50448. enumerable: true,
  50449. configurable: true
  50450. });
  50451. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50452. /**
  50453. * Gets the targeted animations for this animation group
  50454. */
  50455. get: function () {
  50456. return this._targetedAnimations;
  50457. },
  50458. enumerable: true,
  50459. configurable: true
  50460. });
  50461. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50462. /**
  50463. * returning the list of animatables controlled by this animation group.
  50464. */
  50465. get: function () {
  50466. return this._animatables;
  50467. },
  50468. enumerable: true,
  50469. configurable: true
  50470. });
  50471. /**
  50472. * Add an animation (with its target) in the group
  50473. * @param animation defines the animation we want to add
  50474. * @param target defines the target of the animation
  50475. * @returns the {BABYLON.TargetedAnimation} object
  50476. */
  50477. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50478. var targetedAnimation = {
  50479. animation: animation,
  50480. target: target
  50481. };
  50482. var keys = animation.getKeys();
  50483. if (this._from > keys[0].frame) {
  50484. this._from = keys[0].frame;
  50485. }
  50486. if (this._to < keys[keys.length - 1].frame) {
  50487. this._to = keys[keys.length - 1].frame;
  50488. }
  50489. this._targetedAnimations.push(targetedAnimation);
  50490. return targetedAnimation;
  50491. };
  50492. /**
  50493. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50494. * It can add constant keys at begin or end
  50495. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50496. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50497. */
  50498. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50499. if (beginFrame === void 0) { beginFrame = null; }
  50500. if (endFrame === void 0) { endFrame = null; }
  50501. if (beginFrame == null)
  50502. beginFrame = this._from;
  50503. if (endFrame == null)
  50504. endFrame = this._to;
  50505. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50506. var targetedAnimation = this._targetedAnimations[index];
  50507. var keys = targetedAnimation.animation.getKeys();
  50508. var startKey = keys[0];
  50509. var endKey = keys[keys.length - 1];
  50510. if (startKey.frame > beginFrame) {
  50511. var newKey = {
  50512. frame: beginFrame,
  50513. value: startKey.value,
  50514. inTangent: startKey.inTangent,
  50515. outTangent: startKey.outTangent,
  50516. interpolation: startKey.interpolation
  50517. };
  50518. keys.splice(0, 0, newKey);
  50519. }
  50520. if (endKey.frame < endFrame) {
  50521. var newKey = {
  50522. frame: endFrame,
  50523. value: endKey.value,
  50524. inTangent: endKey.outTangent,
  50525. outTangent: endKey.outTangent,
  50526. interpolation: endKey.interpolation
  50527. };
  50528. keys.push(newKey);
  50529. }
  50530. }
  50531. this._from = beginFrame;
  50532. this._to = endFrame;
  50533. return this;
  50534. };
  50535. /**
  50536. * Start all animations on given targets
  50537. * @param loop defines if animations must loop
  50538. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50539. * @param from defines the from key (optional)
  50540. * @param to defines the to key (optional)
  50541. * @returns the current animation group
  50542. */
  50543. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50544. var _this = this;
  50545. if (loop === void 0) { loop = false; }
  50546. if (speedRatio === void 0) { speedRatio = 1; }
  50547. if (this._isStarted || this._targetedAnimations.length === 0) {
  50548. return this;
  50549. }
  50550. var _loop_1 = function (targetedAnimation) {
  50551. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50552. animatable.onAnimationEnd = function () {
  50553. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50554. _this._checkAnimationGroupEnded(animatable);
  50555. };
  50556. this_1._animatables.push(animatable);
  50557. };
  50558. var this_1 = this;
  50559. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50560. var targetedAnimation = _a[_i];
  50561. _loop_1(targetedAnimation);
  50562. }
  50563. this._speedRatio = speedRatio;
  50564. this._isStarted = true;
  50565. return this;
  50566. };
  50567. /**
  50568. * Pause all animations
  50569. */
  50570. AnimationGroup.prototype.pause = function () {
  50571. if (!this._isStarted) {
  50572. return this;
  50573. }
  50574. for (var index = 0; index < this._animatables.length; index++) {
  50575. var animatable = this._animatables[index];
  50576. animatable.pause();
  50577. }
  50578. return this;
  50579. };
  50580. /**
  50581. * Play all animations to initial state
  50582. * This function will start() the animations if they were not started or will restart() them if they were paused
  50583. * @param loop defines if animations must loop
  50584. */
  50585. AnimationGroup.prototype.play = function (loop) {
  50586. // only if all animatables are ready and exist
  50587. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50588. if (loop !== undefined) {
  50589. for (var index = 0; index < this._animatables.length; index++) {
  50590. var animatable = this._animatables[index];
  50591. animatable.loopAnimation = loop;
  50592. }
  50593. }
  50594. this.restart();
  50595. }
  50596. else {
  50597. this.stop();
  50598. this.start(loop, this._speedRatio);
  50599. }
  50600. return this;
  50601. };
  50602. /**
  50603. * Reset all animations to initial state
  50604. */
  50605. AnimationGroup.prototype.reset = function () {
  50606. if (!this._isStarted) {
  50607. return this;
  50608. }
  50609. for (var index = 0; index < this._animatables.length; index++) {
  50610. var animatable = this._animatables[index];
  50611. animatable.reset();
  50612. }
  50613. return this;
  50614. };
  50615. /**
  50616. * Restart animations from key 0
  50617. */
  50618. AnimationGroup.prototype.restart = function () {
  50619. if (!this._isStarted) {
  50620. return this;
  50621. }
  50622. for (var index = 0; index < this._animatables.length; index++) {
  50623. var animatable = this._animatables[index];
  50624. animatable.restart();
  50625. }
  50626. return this;
  50627. };
  50628. /**
  50629. * Stop all animations
  50630. */
  50631. AnimationGroup.prototype.stop = function () {
  50632. if (!this._isStarted) {
  50633. return this;
  50634. }
  50635. var list = this._animatables.slice();
  50636. for (var index = 0; index < list.length; index++) {
  50637. list[index].stop();
  50638. }
  50639. this._isStarted = false;
  50640. return this;
  50641. };
  50642. /**
  50643. * Set animation weight for all animatables
  50644. * @param weight defines the weight to use
  50645. * @return the animationGroup
  50646. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50647. */
  50648. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50649. for (var index = 0; index < this._animatables.length; index++) {
  50650. var animatable = this._animatables[index];
  50651. animatable.weight = weight;
  50652. }
  50653. return this;
  50654. };
  50655. /**
  50656. * Synchronize and normalize all animatables with a source animatable
  50657. * @param root defines the root animatable to synchronize with
  50658. * @return the animationGroup
  50659. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50660. */
  50661. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50662. for (var index = 0; index < this._animatables.length; index++) {
  50663. var animatable = this._animatables[index];
  50664. animatable.syncWith(root);
  50665. }
  50666. return this;
  50667. };
  50668. /**
  50669. * Goes to a specific frame in this animation group
  50670. * @param frame the frame number to go to
  50671. * @return the animationGroup
  50672. */
  50673. AnimationGroup.prototype.goToFrame = function (frame) {
  50674. if (!this._isStarted) {
  50675. return this;
  50676. }
  50677. for (var index = 0; index < this._animatables.length; index++) {
  50678. var animatable = this._animatables[index];
  50679. animatable.goToFrame(frame);
  50680. }
  50681. return this;
  50682. };
  50683. /**
  50684. * Dispose all associated resources
  50685. */
  50686. AnimationGroup.prototype.dispose = function () {
  50687. this._targetedAnimations = [];
  50688. this._animatables = [];
  50689. var index = this._scene.animationGroups.indexOf(this);
  50690. if (index > -1) {
  50691. this._scene.animationGroups.splice(index, 1);
  50692. }
  50693. };
  50694. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50695. // animatable should be taken out of the array
  50696. var idx = this._animatables.indexOf(animatable);
  50697. if (idx > -1) {
  50698. this._animatables.splice(idx, 1);
  50699. }
  50700. // all animatables were removed? animation group ended!
  50701. if (this._animatables.length === 0) {
  50702. this._isStarted = false;
  50703. this.onAnimationGroupEndObservable.notifyObservers(this);
  50704. }
  50705. };
  50706. return AnimationGroup;
  50707. }());
  50708. BABYLON.AnimationGroup = AnimationGroup;
  50709. })(BABYLON || (BABYLON = {}));
  50710. //# sourceMappingURL=babylon.animationGroup.js.map
  50711. var BABYLON;
  50712. (function (BABYLON) {
  50713. /**
  50714. * Defines a runtime animation
  50715. */
  50716. var RuntimeAnimation = /** @class */ (function () {
  50717. /**
  50718. * Create a new RuntimeAnimation object
  50719. * @param target defines the target of the animation
  50720. * @param animation defines the source animation object
  50721. * @param scene defines the hosting scene
  50722. * @param host defines the initiating Animatable
  50723. */
  50724. function RuntimeAnimation(target, animation, scene, host) {
  50725. var _this = this;
  50726. this._events = new Array();
  50727. /**
  50728. * The current frame of the runtime animation
  50729. */
  50730. this._currentFrame = 0;
  50731. /**
  50732. * The original value of the runtime animation
  50733. */
  50734. this._originalValue = new Array();
  50735. /**
  50736. * The offsets cache of the runtime animation
  50737. */
  50738. this._offsetsCache = {};
  50739. /**
  50740. * The high limits cache of the runtime animation
  50741. */
  50742. this._highLimitsCache = {};
  50743. /**
  50744. * Specifies if the runtime animation has been stopped
  50745. */
  50746. this._stopped = false;
  50747. /**
  50748. * The blending factor of the runtime animation
  50749. */
  50750. this._blendingFactor = 0;
  50751. /**
  50752. * The target path of the runtime animation
  50753. */
  50754. this._targetPath = "";
  50755. /**
  50756. * The weight of the runtime animation
  50757. */
  50758. this._weight = 1.0;
  50759. /**
  50760. * The ratio offset of the runtime animation
  50761. */
  50762. this._ratioOffset = 0;
  50763. /**
  50764. * The previous delay of the runtime animation
  50765. */
  50766. this._previousDelay = 0;
  50767. /**
  50768. * The previous ratio of the runtime animation
  50769. */
  50770. this._previousRatio = 0;
  50771. this._animation = animation;
  50772. this._target = target;
  50773. this._scene = scene;
  50774. this._host = host;
  50775. animation._runtimeAnimations.push(this);
  50776. // Cloning events locally
  50777. var events = animation.getEvents();
  50778. if (events && events.length > 0) {
  50779. events.forEach(function (e) {
  50780. _this._events.push(e._clone());
  50781. });
  50782. }
  50783. }
  50784. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50785. /**
  50786. * Gets the current frame of the runtime animation
  50787. */
  50788. get: function () {
  50789. return this._currentFrame;
  50790. },
  50791. enumerable: true,
  50792. configurable: true
  50793. });
  50794. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50795. /**
  50796. * Gets the weight of the runtime animation
  50797. */
  50798. get: function () {
  50799. return this._weight;
  50800. },
  50801. enumerable: true,
  50802. configurable: true
  50803. });
  50804. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50805. /**
  50806. * Gets the current value of the runtime animation
  50807. */
  50808. get: function () {
  50809. return this._currentValue;
  50810. },
  50811. enumerable: true,
  50812. configurable: true
  50813. });
  50814. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50815. /**
  50816. * Gets the target path of the runtime animation
  50817. */
  50818. get: function () {
  50819. return this._targetPath;
  50820. },
  50821. enumerable: true,
  50822. configurable: true
  50823. });
  50824. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50825. /**
  50826. * Gets the actual target of the runtime animation
  50827. */
  50828. get: function () {
  50829. return this._activeTarget;
  50830. },
  50831. enumerable: true,
  50832. configurable: true
  50833. });
  50834. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50835. /**
  50836. * Gets the animation from the runtime animation
  50837. */
  50838. get: function () {
  50839. return this._animation;
  50840. },
  50841. enumerable: true,
  50842. configurable: true
  50843. });
  50844. /**
  50845. * Resets the runtime animation to the beginning
  50846. * @param restoreOriginal defines whether to restore the target property to the original value
  50847. */
  50848. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50849. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50850. if (restoreOriginal) {
  50851. if (this._target instanceof Array) {
  50852. var index = 0;
  50853. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50854. var target = _a[_i];
  50855. if (this._originalValue[index] !== undefined) {
  50856. this._setValue(target, this._originalValue[index], -1);
  50857. }
  50858. index++;
  50859. }
  50860. }
  50861. else {
  50862. if (this._originalValue[0] !== undefined) {
  50863. this._setValue(this._target, this._originalValue[0], -1);
  50864. }
  50865. }
  50866. }
  50867. this._offsetsCache = {};
  50868. this._highLimitsCache = {};
  50869. this._currentFrame = 0;
  50870. this._blendingFactor = 0;
  50871. this._originalValue = new Array();
  50872. // Events
  50873. for (var index = 0; index < this._events.length; index++) {
  50874. this._events[index].isDone = false;
  50875. }
  50876. };
  50877. /**
  50878. * Specifies if the runtime animation is stopped
  50879. * @returns Boolean specifying if the runtime animation is stopped
  50880. */
  50881. RuntimeAnimation.prototype.isStopped = function () {
  50882. return this._stopped;
  50883. };
  50884. /**
  50885. * Disposes of the runtime animation
  50886. */
  50887. RuntimeAnimation.prototype.dispose = function () {
  50888. var index = this._animation.runtimeAnimations.indexOf(this);
  50889. if (index > -1) {
  50890. this._animation.runtimeAnimations.splice(index, 1);
  50891. }
  50892. };
  50893. /**
  50894. * Interpolates the animation from the current frame
  50895. * @param currentFrame The frame to interpolate the animation to
  50896. * @param repeatCount The number of times that the animation should loop
  50897. * @param loopMode The type of looping mode to use
  50898. * @param offsetValue Animation offset value
  50899. * @param highLimitValue The high limit value
  50900. * @returns The interpolated value
  50901. */
  50902. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50903. this._currentFrame = currentFrame;
  50904. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50905. this._workValue = BABYLON.Matrix.Zero();
  50906. }
  50907. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50908. };
  50909. /**
  50910. * Apply the interpolated value to the target
  50911. * @param currentValue defines the value computed by the animation
  50912. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50913. */
  50914. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50915. if (weight === void 0) { weight = 1.0; }
  50916. if (this._target instanceof Array) {
  50917. var index = 0;
  50918. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50919. var target = _a[_i];
  50920. this._setValue(target, currentValue, weight, index);
  50921. index++;
  50922. }
  50923. }
  50924. else {
  50925. this._setValue(this._target, currentValue, weight);
  50926. }
  50927. };
  50928. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  50929. if (targetIndex === void 0) { targetIndex = 0; }
  50930. // Set value
  50931. var path;
  50932. var destination;
  50933. var targetPropertyPath = this._animation.targetPropertyPath;
  50934. if (targetPropertyPath.length > 1) {
  50935. var property = target[targetPropertyPath[0]];
  50936. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  50937. property = property[targetPropertyPath[index]];
  50938. }
  50939. path = targetPropertyPath[targetPropertyPath.length - 1];
  50940. destination = property;
  50941. }
  50942. else {
  50943. path = targetPropertyPath[0];
  50944. destination = target;
  50945. }
  50946. this._targetPath = path;
  50947. this._activeTarget = destination;
  50948. this._weight = weight;
  50949. if (this._originalValue[targetIndex] === undefined) {
  50950. var originalValue = void 0;
  50951. if (destination.getRestPose && path === "_matrix") { // For bones
  50952. originalValue = destination.getRestPose();
  50953. }
  50954. else {
  50955. originalValue = destination[path];
  50956. }
  50957. if (originalValue && originalValue.clone) {
  50958. this._originalValue[targetIndex] = originalValue.clone();
  50959. }
  50960. else {
  50961. this._originalValue[targetIndex] = originalValue;
  50962. }
  50963. }
  50964. // Blending
  50965. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  50966. if (enableBlending && this._blendingFactor <= 1.0) {
  50967. if (!this._originalBlendValue) {
  50968. var originalValue = destination[path];
  50969. if (originalValue.clone) {
  50970. this._originalBlendValue = originalValue.clone();
  50971. }
  50972. else {
  50973. this._originalBlendValue = originalValue;
  50974. }
  50975. }
  50976. if (this._originalBlendValue.m) { // Matrix
  50977. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  50978. if (this._currentValue) {
  50979. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50980. }
  50981. else {
  50982. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50983. }
  50984. }
  50985. else {
  50986. if (this._currentValue) {
  50987. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  50988. }
  50989. else {
  50990. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50991. }
  50992. }
  50993. }
  50994. else {
  50995. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  50996. }
  50997. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  50998. this._blendingFactor += blendingSpeed;
  50999. }
  51000. else {
  51001. this._currentValue = currentValue;
  51002. }
  51003. if (weight !== -1.0) {
  51004. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51005. }
  51006. else {
  51007. destination[path] = this._currentValue;
  51008. }
  51009. if (target.markAsDirty) {
  51010. target.markAsDirty(this._animation.targetProperty);
  51011. }
  51012. };
  51013. /**
  51014. * Gets the loop pmode of the runtime animation
  51015. * @returns Loop Mode
  51016. */
  51017. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51018. if (this._target && this._target.animationPropertiesOverride) {
  51019. return this._target.animationPropertiesOverride.loopMode;
  51020. }
  51021. return this._animation.loopMode;
  51022. };
  51023. /**
  51024. * Move the current animation to a given frame
  51025. * @param frame defines the frame to move to
  51026. */
  51027. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51028. var keys = this._animation.getKeys();
  51029. if (frame < keys[0].frame) {
  51030. frame = keys[0].frame;
  51031. }
  51032. else if (frame > keys[keys.length - 1].frame) {
  51033. frame = keys[keys.length - 1].frame;
  51034. }
  51035. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51036. this.setValue(currentValue, -1);
  51037. };
  51038. /**
  51039. * @hidden Internal use only
  51040. */
  51041. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51042. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51043. this._ratioOffset = this._previousRatio - newRatio;
  51044. };
  51045. /**
  51046. * Execute the current animation
  51047. * @param delay defines the delay to add to the current frame
  51048. * @param from defines the lower bound of the animation range
  51049. * @param to defines the upper bound of the animation range
  51050. * @param loop defines if the current animation must loop
  51051. * @param speedRatio defines the current speed ratio
  51052. * @param weight defines the weight of the animation (default is -1 so no weight)
  51053. * @returns a boolean indicating if the animation has ended
  51054. */
  51055. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51056. if (weight === void 0) { weight = -1.0; }
  51057. var targetPropertyPath = this._animation.targetPropertyPath;
  51058. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51059. this._stopped = true;
  51060. return false;
  51061. }
  51062. var returnValue = true;
  51063. var keys = this._animation.getKeys();
  51064. // Adding a start key at frame 0 if missing
  51065. if (keys[0].frame !== 0) {
  51066. var newKey = { frame: 0, value: keys[0].value };
  51067. keys.splice(0, 0, newKey);
  51068. }
  51069. // Check limits
  51070. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51071. from = keys[0].frame;
  51072. }
  51073. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51074. to = keys[keys.length - 1].frame;
  51075. }
  51076. //to and from cannot be the same key
  51077. if (from === to) {
  51078. if (from > keys[0].frame) {
  51079. from--;
  51080. }
  51081. else if (to < keys[keys.length - 1].frame) {
  51082. to++;
  51083. }
  51084. }
  51085. // Compute ratio
  51086. var range = to - from;
  51087. var offsetValue;
  51088. // ratio represents the frame delta between from and to
  51089. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51090. var highLimitValue = 0;
  51091. this._previousDelay = delay;
  51092. this._previousRatio = ratio;
  51093. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51094. returnValue = false;
  51095. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51096. }
  51097. else {
  51098. // Get max value if required
  51099. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51100. var keyOffset = to.toString() + from.toString();
  51101. if (!this._offsetsCache[keyOffset]) {
  51102. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51103. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51104. switch (this._animation.dataType) {
  51105. // Float
  51106. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51107. this._offsetsCache[keyOffset] = toValue - fromValue;
  51108. break;
  51109. // Quaternion
  51110. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51111. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51112. break;
  51113. // Vector3
  51114. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51115. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51116. // Vector2
  51117. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51118. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51119. // Size
  51120. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51121. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51122. // Color3
  51123. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51124. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51125. default:
  51126. break;
  51127. }
  51128. this._highLimitsCache[keyOffset] = toValue;
  51129. }
  51130. highLimitValue = this._highLimitsCache[keyOffset];
  51131. offsetValue = this._offsetsCache[keyOffset];
  51132. }
  51133. }
  51134. if (offsetValue === undefined) {
  51135. switch (this._animation.dataType) {
  51136. // Float
  51137. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51138. offsetValue = 0;
  51139. break;
  51140. // Quaternion
  51141. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51142. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51143. break;
  51144. // Vector3
  51145. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51146. offsetValue = BABYLON.Vector3.Zero();
  51147. break;
  51148. // Vector2
  51149. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51150. offsetValue = BABYLON.Vector2.Zero();
  51151. break;
  51152. // Size
  51153. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51154. offsetValue = BABYLON.Size.Zero();
  51155. break;
  51156. // Color3
  51157. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51158. offsetValue = BABYLON.Color3.Black();
  51159. }
  51160. }
  51161. // Compute value
  51162. var repeatCount = (ratio / range) >> 0;
  51163. var currentFrame = returnValue ? from + ratio % range : to;
  51164. // Need to normalize?
  51165. if (this._host && this._host.syncRoot) {
  51166. var syncRoot = this._host.syncRoot;
  51167. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51168. currentFrame = from + (to - from) * hostNormalizedFrame;
  51169. }
  51170. // Reset events if looping
  51171. var events = this._events;
  51172. if (range > 0 && this.currentFrame > currentFrame ||
  51173. range < 0 && this.currentFrame < currentFrame) {
  51174. // Need to reset animation events
  51175. for (var index = 0; index < events.length; index++) {
  51176. if (!events[index].onlyOnce) {
  51177. // reset event, the animation is looping
  51178. events[index].isDone = false;
  51179. }
  51180. }
  51181. }
  51182. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51183. // Set value
  51184. this.setValue(currentValue, weight);
  51185. // Check events
  51186. for (var index = 0; index < events.length; index++) {
  51187. // Make sure current frame has passed event frame and that event frame is within the current range
  51188. // Also, handle both forward and reverse animations
  51189. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51190. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51191. var event = events[index];
  51192. if (!event.isDone) {
  51193. // If event should be done only once, remove it.
  51194. if (event.onlyOnce) {
  51195. events.splice(index, 1);
  51196. index--;
  51197. }
  51198. event.isDone = true;
  51199. event.action();
  51200. } // Don't do anything if the event has already be done.
  51201. }
  51202. }
  51203. if (!returnValue) {
  51204. this._stopped = true;
  51205. }
  51206. return returnValue;
  51207. };
  51208. return RuntimeAnimation;
  51209. }());
  51210. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51211. })(BABYLON || (BABYLON = {}));
  51212. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51213. var BABYLON;
  51214. (function (BABYLON) {
  51215. var Animatable = /** @class */ (function () {
  51216. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51217. if (fromFrame === void 0) { fromFrame = 0; }
  51218. if (toFrame === void 0) { toFrame = 100; }
  51219. if (loopAnimation === void 0) { loopAnimation = false; }
  51220. if (speedRatio === void 0) { speedRatio = 1.0; }
  51221. this.target = target;
  51222. this.fromFrame = fromFrame;
  51223. this.toFrame = toFrame;
  51224. this.loopAnimation = loopAnimation;
  51225. this.onAnimationEnd = onAnimationEnd;
  51226. this._localDelayOffset = null;
  51227. this._pausedDelay = null;
  51228. this._runtimeAnimations = new Array();
  51229. this._paused = false;
  51230. this._speedRatio = 1;
  51231. this._weight = -1.0;
  51232. this.animationStarted = false;
  51233. /**
  51234. * Observer raised when the animation ends
  51235. */
  51236. this.onAnimationEndObservable = new BABYLON.Observable();
  51237. this._scene = scene;
  51238. if (animations) {
  51239. this.appendAnimations(target, animations);
  51240. }
  51241. this._speedRatio = speedRatio;
  51242. scene._activeAnimatables.push(this);
  51243. }
  51244. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51245. /**
  51246. * Gets the root Animatable used to synchronize and normalize animations
  51247. */
  51248. get: function () {
  51249. return this._syncRoot;
  51250. },
  51251. enumerable: true,
  51252. configurable: true
  51253. });
  51254. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51255. /**
  51256. * Gets the current frame of the first RuntimeAnimation
  51257. * Used to synchronize Animatables
  51258. */
  51259. get: function () {
  51260. if (this._runtimeAnimations.length === 0) {
  51261. return 0;
  51262. }
  51263. return this._runtimeAnimations[0].currentFrame;
  51264. },
  51265. enumerable: true,
  51266. configurable: true
  51267. });
  51268. Object.defineProperty(Animatable.prototype, "weight", {
  51269. /**
  51270. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51271. */
  51272. get: function () {
  51273. return this._weight;
  51274. },
  51275. set: function (value) {
  51276. if (value === -1) { // -1 is ok and means no weight
  51277. this._weight = -1;
  51278. return;
  51279. }
  51280. // Else weight must be in [0, 1] range
  51281. this._weight = Math.min(Math.max(value, 0), 1.0);
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51287. /**
  51288. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51289. */
  51290. get: function () {
  51291. return this._speedRatio;
  51292. },
  51293. set: function (value) {
  51294. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51295. var animation = this._runtimeAnimations[index];
  51296. animation._prepareForSpeedRatioChange(value);
  51297. }
  51298. this._speedRatio = value;
  51299. },
  51300. enumerable: true,
  51301. configurable: true
  51302. });
  51303. // Methods
  51304. /**
  51305. * Synchronize and normalize current Animatable with a source Animatable
  51306. * This is useful when using animation weights and when animations are not of the same length
  51307. * @param root defines the root Animatable to synchronize with
  51308. * @returns the current Animatable
  51309. */
  51310. Animatable.prototype.syncWith = function (root) {
  51311. this._syncRoot = root;
  51312. if (root) {
  51313. // Make sure this animatable will animate after the root
  51314. var index = this._scene._activeAnimatables.indexOf(this);
  51315. if (index > -1) {
  51316. this._scene._activeAnimatables.splice(index, 1);
  51317. this._scene._activeAnimatables.push(this);
  51318. }
  51319. }
  51320. return this;
  51321. };
  51322. Animatable.prototype.getAnimations = function () {
  51323. return this._runtimeAnimations;
  51324. };
  51325. Animatable.prototype.appendAnimations = function (target, animations) {
  51326. for (var index = 0; index < animations.length; index++) {
  51327. var animation = animations[index];
  51328. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51329. }
  51330. };
  51331. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51332. var runtimeAnimations = this._runtimeAnimations;
  51333. for (var index = 0; index < runtimeAnimations.length; index++) {
  51334. if (runtimeAnimations[index].animation.targetProperty === property) {
  51335. return runtimeAnimations[index].animation;
  51336. }
  51337. }
  51338. return null;
  51339. };
  51340. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51341. var runtimeAnimations = this._runtimeAnimations;
  51342. for (var index = 0; index < runtimeAnimations.length; index++) {
  51343. if (runtimeAnimations[index].animation.targetProperty === property) {
  51344. return runtimeAnimations[index];
  51345. }
  51346. }
  51347. return null;
  51348. };
  51349. Animatable.prototype.reset = function () {
  51350. var runtimeAnimations = this._runtimeAnimations;
  51351. for (var index = 0; index < runtimeAnimations.length; index++) {
  51352. runtimeAnimations[index].reset(true);
  51353. }
  51354. this._localDelayOffset = null;
  51355. this._pausedDelay = null;
  51356. };
  51357. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51358. var runtimeAnimations = this._runtimeAnimations;
  51359. for (var index = 0; index < runtimeAnimations.length; index++) {
  51360. runtimeAnimations[index].animation.enableBlending = true;
  51361. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51362. }
  51363. };
  51364. Animatable.prototype.disableBlending = function () {
  51365. var runtimeAnimations = this._runtimeAnimations;
  51366. for (var index = 0; index < runtimeAnimations.length; index++) {
  51367. runtimeAnimations[index].animation.enableBlending = false;
  51368. }
  51369. };
  51370. Animatable.prototype.goToFrame = function (frame) {
  51371. var runtimeAnimations = this._runtimeAnimations;
  51372. if (runtimeAnimations[0]) {
  51373. var fps = runtimeAnimations[0].animation.framePerSecond;
  51374. var currentFrame = runtimeAnimations[0].currentFrame;
  51375. var adjustTime = frame - currentFrame;
  51376. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51377. if (this._localDelayOffset === null) {
  51378. this._localDelayOffset = 0;
  51379. }
  51380. this._localDelayOffset -= delay;
  51381. }
  51382. for (var index = 0; index < runtimeAnimations.length; index++) {
  51383. runtimeAnimations[index].goToFrame(frame);
  51384. }
  51385. };
  51386. Animatable.prototype.pause = function () {
  51387. if (this._paused) {
  51388. return;
  51389. }
  51390. this._paused = true;
  51391. };
  51392. Animatable.prototype.restart = function () {
  51393. this._paused = false;
  51394. };
  51395. Animatable.prototype._raiseOnAnimationEnd = function () {
  51396. if (this.onAnimationEnd) {
  51397. this.onAnimationEnd();
  51398. }
  51399. this.onAnimationEndObservable.notifyObservers(this);
  51400. };
  51401. Animatable.prototype.stop = function (animationName) {
  51402. if (animationName) {
  51403. var idx = this._scene._activeAnimatables.indexOf(this);
  51404. if (idx > -1) {
  51405. var runtimeAnimations = this._runtimeAnimations;
  51406. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51407. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51408. continue;
  51409. }
  51410. runtimeAnimations[index].dispose();
  51411. runtimeAnimations.splice(index, 1);
  51412. }
  51413. if (runtimeAnimations.length == 0) {
  51414. this._scene._activeAnimatables.splice(idx, 1);
  51415. this._raiseOnAnimationEnd();
  51416. }
  51417. }
  51418. }
  51419. else {
  51420. var index = this._scene._activeAnimatables.indexOf(this);
  51421. if (index > -1) {
  51422. this._scene._activeAnimatables.splice(index, 1);
  51423. var runtimeAnimations = this._runtimeAnimations;
  51424. for (var index = 0; index < runtimeAnimations.length; index++) {
  51425. runtimeAnimations[index].dispose();
  51426. }
  51427. this._raiseOnAnimationEnd();
  51428. }
  51429. }
  51430. };
  51431. /**
  51432. * Wait asynchronously for the animation to end
  51433. * @returns a promise which will be fullfilled when the animation ends
  51434. */
  51435. Animatable.prototype.waitAsync = function () {
  51436. var _this = this;
  51437. return new Promise(function (resolve, reject) {
  51438. _this.onAnimationEndObservable.add(function () {
  51439. resolve(_this);
  51440. }, undefined, undefined, _this, true);
  51441. });
  51442. };
  51443. /** @hidden */
  51444. Animatable.prototype._animate = function (delay) {
  51445. if (this._paused) {
  51446. this.animationStarted = false;
  51447. if (this._pausedDelay === null) {
  51448. this._pausedDelay = delay;
  51449. }
  51450. return true;
  51451. }
  51452. if (this._localDelayOffset === null) {
  51453. this._localDelayOffset = delay;
  51454. this._pausedDelay = null;
  51455. }
  51456. else if (this._pausedDelay !== null) {
  51457. this._localDelayOffset += delay - this._pausedDelay;
  51458. this._pausedDelay = null;
  51459. }
  51460. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51461. return true;
  51462. }
  51463. // Animating
  51464. var running = false;
  51465. var runtimeAnimations = this._runtimeAnimations;
  51466. var index;
  51467. for (index = 0; index < runtimeAnimations.length; index++) {
  51468. var animation = runtimeAnimations[index];
  51469. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51470. running = running || isRunning;
  51471. }
  51472. this.animationStarted = running;
  51473. if (!running) {
  51474. // Remove from active animatables
  51475. index = this._scene._activeAnimatables.indexOf(this);
  51476. this._scene._activeAnimatables.splice(index, 1);
  51477. // Dispose all runtime animations
  51478. for (index = 0; index < runtimeAnimations.length; index++) {
  51479. runtimeAnimations[index].dispose();
  51480. }
  51481. this._raiseOnAnimationEnd();
  51482. this.onAnimationEnd = null;
  51483. this.onAnimationEndObservable.clear();
  51484. }
  51485. return running;
  51486. };
  51487. return Animatable;
  51488. }());
  51489. BABYLON.Animatable = Animatable;
  51490. })(BABYLON || (BABYLON = {}));
  51491. //# sourceMappingURL=babylon.animatable.js.map
  51492. var BABYLON;
  51493. (function (BABYLON) {
  51494. var EasingFunction = /** @class */ (function () {
  51495. function EasingFunction() {
  51496. // Properties
  51497. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51498. }
  51499. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51500. get: function () {
  51501. return EasingFunction._EASINGMODE_EASEIN;
  51502. },
  51503. enumerable: true,
  51504. configurable: true
  51505. });
  51506. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51507. get: function () {
  51508. return EasingFunction._EASINGMODE_EASEOUT;
  51509. },
  51510. enumerable: true,
  51511. configurable: true
  51512. });
  51513. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51514. get: function () {
  51515. return EasingFunction._EASINGMODE_EASEINOUT;
  51516. },
  51517. enumerable: true,
  51518. configurable: true
  51519. });
  51520. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51521. var n = Math.min(Math.max(easingMode, 0), 2);
  51522. this._easingMode = n;
  51523. };
  51524. EasingFunction.prototype.getEasingMode = function () {
  51525. return this._easingMode;
  51526. };
  51527. EasingFunction.prototype.easeInCore = function (gradient) {
  51528. throw new Error('You must implement this method');
  51529. };
  51530. EasingFunction.prototype.ease = function (gradient) {
  51531. switch (this._easingMode) {
  51532. case EasingFunction.EASINGMODE_EASEIN:
  51533. return this.easeInCore(gradient);
  51534. case EasingFunction.EASINGMODE_EASEOUT:
  51535. return (1 - this.easeInCore(1 - gradient));
  51536. }
  51537. if (gradient >= 0.5) {
  51538. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51539. }
  51540. return (this.easeInCore(gradient * 2) * 0.5);
  51541. };
  51542. //Statics
  51543. EasingFunction._EASINGMODE_EASEIN = 0;
  51544. EasingFunction._EASINGMODE_EASEOUT = 1;
  51545. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51546. return EasingFunction;
  51547. }());
  51548. BABYLON.EasingFunction = EasingFunction;
  51549. var CircleEase = /** @class */ (function (_super) {
  51550. __extends(CircleEase, _super);
  51551. function CircleEase() {
  51552. return _super !== null && _super.apply(this, arguments) || this;
  51553. }
  51554. CircleEase.prototype.easeInCore = function (gradient) {
  51555. gradient = Math.max(0, Math.min(1, gradient));
  51556. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51557. };
  51558. return CircleEase;
  51559. }(EasingFunction));
  51560. BABYLON.CircleEase = CircleEase;
  51561. var BackEase = /** @class */ (function (_super) {
  51562. __extends(BackEase, _super);
  51563. function BackEase(amplitude) {
  51564. if (amplitude === void 0) { amplitude = 1; }
  51565. var _this = _super.call(this) || this;
  51566. _this.amplitude = amplitude;
  51567. return _this;
  51568. }
  51569. BackEase.prototype.easeInCore = function (gradient) {
  51570. var num = Math.max(0, this.amplitude);
  51571. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51572. };
  51573. return BackEase;
  51574. }(EasingFunction));
  51575. BABYLON.BackEase = BackEase;
  51576. var BounceEase = /** @class */ (function (_super) {
  51577. __extends(BounceEase, _super);
  51578. function BounceEase(bounces, bounciness) {
  51579. if (bounces === void 0) { bounces = 3; }
  51580. if (bounciness === void 0) { bounciness = 2; }
  51581. var _this = _super.call(this) || this;
  51582. _this.bounces = bounces;
  51583. _this.bounciness = bounciness;
  51584. return _this;
  51585. }
  51586. BounceEase.prototype.easeInCore = function (gradient) {
  51587. var y = Math.max(0.0, this.bounces);
  51588. var bounciness = this.bounciness;
  51589. if (bounciness <= 1.0) {
  51590. bounciness = 1.001;
  51591. }
  51592. var num9 = Math.pow(bounciness, y);
  51593. var num5 = 1.0 - bounciness;
  51594. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51595. var num15 = gradient * num4;
  51596. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51597. var num3 = Math.floor(num65);
  51598. var num13 = num3 + 1.0;
  51599. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51600. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51601. var num7 = (num8 + num12) * 0.5;
  51602. var num6 = gradient - num7;
  51603. var num2 = num7 - num8;
  51604. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51605. };
  51606. return BounceEase;
  51607. }(EasingFunction));
  51608. BABYLON.BounceEase = BounceEase;
  51609. var CubicEase = /** @class */ (function (_super) {
  51610. __extends(CubicEase, _super);
  51611. function CubicEase() {
  51612. return _super !== null && _super.apply(this, arguments) || this;
  51613. }
  51614. CubicEase.prototype.easeInCore = function (gradient) {
  51615. return (gradient * gradient * gradient);
  51616. };
  51617. return CubicEase;
  51618. }(EasingFunction));
  51619. BABYLON.CubicEase = CubicEase;
  51620. var ElasticEase = /** @class */ (function (_super) {
  51621. __extends(ElasticEase, _super);
  51622. function ElasticEase(oscillations, springiness) {
  51623. if (oscillations === void 0) { oscillations = 3; }
  51624. if (springiness === void 0) { springiness = 3; }
  51625. var _this = _super.call(this) || this;
  51626. _this.oscillations = oscillations;
  51627. _this.springiness = springiness;
  51628. return _this;
  51629. }
  51630. ElasticEase.prototype.easeInCore = function (gradient) {
  51631. var num2;
  51632. var num3 = Math.max(0.0, this.oscillations);
  51633. var num = Math.max(0.0, this.springiness);
  51634. if (num == 0) {
  51635. num2 = gradient;
  51636. }
  51637. else {
  51638. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51639. }
  51640. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51641. };
  51642. return ElasticEase;
  51643. }(EasingFunction));
  51644. BABYLON.ElasticEase = ElasticEase;
  51645. var ExponentialEase = /** @class */ (function (_super) {
  51646. __extends(ExponentialEase, _super);
  51647. function ExponentialEase(exponent) {
  51648. if (exponent === void 0) { exponent = 2; }
  51649. var _this = _super.call(this) || this;
  51650. _this.exponent = exponent;
  51651. return _this;
  51652. }
  51653. ExponentialEase.prototype.easeInCore = function (gradient) {
  51654. if (this.exponent <= 0) {
  51655. return gradient;
  51656. }
  51657. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51658. };
  51659. return ExponentialEase;
  51660. }(EasingFunction));
  51661. BABYLON.ExponentialEase = ExponentialEase;
  51662. var PowerEase = /** @class */ (function (_super) {
  51663. __extends(PowerEase, _super);
  51664. function PowerEase(power) {
  51665. if (power === void 0) { power = 2; }
  51666. var _this = _super.call(this) || this;
  51667. _this.power = power;
  51668. return _this;
  51669. }
  51670. PowerEase.prototype.easeInCore = function (gradient) {
  51671. var y = Math.max(0.0, this.power);
  51672. return Math.pow(gradient, y);
  51673. };
  51674. return PowerEase;
  51675. }(EasingFunction));
  51676. BABYLON.PowerEase = PowerEase;
  51677. var QuadraticEase = /** @class */ (function (_super) {
  51678. __extends(QuadraticEase, _super);
  51679. function QuadraticEase() {
  51680. return _super !== null && _super.apply(this, arguments) || this;
  51681. }
  51682. QuadraticEase.prototype.easeInCore = function (gradient) {
  51683. return (gradient * gradient);
  51684. };
  51685. return QuadraticEase;
  51686. }(EasingFunction));
  51687. BABYLON.QuadraticEase = QuadraticEase;
  51688. var QuarticEase = /** @class */ (function (_super) {
  51689. __extends(QuarticEase, _super);
  51690. function QuarticEase() {
  51691. return _super !== null && _super.apply(this, arguments) || this;
  51692. }
  51693. QuarticEase.prototype.easeInCore = function (gradient) {
  51694. return (gradient * gradient * gradient * gradient);
  51695. };
  51696. return QuarticEase;
  51697. }(EasingFunction));
  51698. BABYLON.QuarticEase = QuarticEase;
  51699. var QuinticEase = /** @class */ (function (_super) {
  51700. __extends(QuinticEase, _super);
  51701. function QuinticEase() {
  51702. return _super !== null && _super.apply(this, arguments) || this;
  51703. }
  51704. QuinticEase.prototype.easeInCore = function (gradient) {
  51705. return (gradient * gradient * gradient * gradient * gradient);
  51706. };
  51707. return QuinticEase;
  51708. }(EasingFunction));
  51709. BABYLON.QuinticEase = QuinticEase;
  51710. var SineEase = /** @class */ (function (_super) {
  51711. __extends(SineEase, _super);
  51712. function SineEase() {
  51713. return _super !== null && _super.apply(this, arguments) || this;
  51714. }
  51715. SineEase.prototype.easeInCore = function (gradient) {
  51716. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51717. };
  51718. return SineEase;
  51719. }(EasingFunction));
  51720. BABYLON.SineEase = SineEase;
  51721. var BezierCurveEase = /** @class */ (function (_super) {
  51722. __extends(BezierCurveEase, _super);
  51723. function BezierCurveEase(x1, y1, x2, y2) {
  51724. if (x1 === void 0) { x1 = 0; }
  51725. if (y1 === void 0) { y1 = 0; }
  51726. if (x2 === void 0) { x2 = 1; }
  51727. if (y2 === void 0) { y2 = 1; }
  51728. var _this = _super.call(this) || this;
  51729. _this.x1 = x1;
  51730. _this.y1 = y1;
  51731. _this.x2 = x2;
  51732. _this.y2 = y2;
  51733. return _this;
  51734. }
  51735. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51736. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51737. };
  51738. return BezierCurveEase;
  51739. }(EasingFunction));
  51740. BABYLON.BezierCurveEase = BezierCurveEase;
  51741. })(BABYLON || (BABYLON = {}));
  51742. //# sourceMappingURL=babylon.easing.js.map
  51743. var BABYLON;
  51744. (function (BABYLON) {
  51745. /**
  51746. * A Condition applied to an Action
  51747. */
  51748. var Condition = /** @class */ (function () {
  51749. /**
  51750. * Creates a new Condition
  51751. * @param actionManager the manager of the action the condition is applied to
  51752. */
  51753. function Condition(actionManager) {
  51754. this._actionManager = actionManager;
  51755. }
  51756. /**
  51757. * Check if the current condition is valid
  51758. * @returns a boolean
  51759. */
  51760. Condition.prototype.isValid = function () {
  51761. return true;
  51762. };
  51763. /**
  51764. * Internal only
  51765. * @hidden
  51766. */
  51767. Condition.prototype._getProperty = function (propertyPath) {
  51768. return this._actionManager._getProperty(propertyPath);
  51769. };
  51770. /**
  51771. * Internal only
  51772. * @hidden
  51773. */
  51774. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51775. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51776. };
  51777. /**
  51778. * Serialize placeholder for child classes
  51779. * @returns the serialized object
  51780. */
  51781. Condition.prototype.serialize = function () {
  51782. };
  51783. /**
  51784. * Internal only
  51785. * @hidden
  51786. */
  51787. Condition.prototype._serialize = function (serializedCondition) {
  51788. return {
  51789. type: 2,
  51790. children: [],
  51791. name: serializedCondition.name,
  51792. properties: serializedCondition.properties
  51793. };
  51794. };
  51795. return Condition;
  51796. }());
  51797. BABYLON.Condition = Condition;
  51798. /**
  51799. * Defines specific conditional operators as extensions of Condition
  51800. */
  51801. var ValueCondition = /** @class */ (function (_super) {
  51802. __extends(ValueCondition, _super);
  51803. /**
  51804. * Creates a new ValueCondition
  51805. * @param actionManager manager for the action the condition applies to
  51806. * @param target for the action
  51807. * @param propertyPath path to specify the property of the target the conditional operator uses
  51808. * @param value the value compared by the conditional operator against the current value of the property
  51809. * @param operator the conditional operator, default ValueCondition.IsEqual
  51810. */
  51811. function ValueCondition(actionManager, target,
  51812. /** path to specify the property of the target the conditional operator uses */
  51813. propertyPath,
  51814. /** the value compared by the conditional operator against the current value of the property */
  51815. value,
  51816. /** the conditional operator, default ValueCondition.IsEqual */
  51817. operator) {
  51818. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51819. var _this = _super.call(this, actionManager) || this;
  51820. _this.propertyPath = propertyPath;
  51821. _this.value = value;
  51822. _this.operator = operator;
  51823. _this._target = target;
  51824. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51825. _this._property = _this._getProperty(_this.propertyPath);
  51826. return _this;
  51827. }
  51828. Object.defineProperty(ValueCondition, "IsEqual", {
  51829. /**
  51830. * returns the number for IsEqual
  51831. */
  51832. get: function () {
  51833. return ValueCondition._IsEqual;
  51834. },
  51835. enumerable: true,
  51836. configurable: true
  51837. });
  51838. Object.defineProperty(ValueCondition, "IsDifferent", {
  51839. /**
  51840. * Returns the number for IsDifferent
  51841. */
  51842. get: function () {
  51843. return ValueCondition._IsDifferent;
  51844. },
  51845. enumerable: true,
  51846. configurable: true
  51847. });
  51848. Object.defineProperty(ValueCondition, "IsGreater", {
  51849. /**
  51850. * Returns the number for IsGreater
  51851. */
  51852. get: function () {
  51853. return ValueCondition._IsGreater;
  51854. },
  51855. enumerable: true,
  51856. configurable: true
  51857. });
  51858. Object.defineProperty(ValueCondition, "IsLesser", {
  51859. /**
  51860. * Returns the number for IsLesser
  51861. */
  51862. get: function () {
  51863. return ValueCondition._IsLesser;
  51864. },
  51865. enumerable: true,
  51866. configurable: true
  51867. });
  51868. /**
  51869. * Compares the given value with the property value for the specified conditional operator
  51870. * @returns the result of the comparison
  51871. */
  51872. ValueCondition.prototype.isValid = function () {
  51873. switch (this.operator) {
  51874. case ValueCondition.IsGreater:
  51875. return this._effectiveTarget[this._property] > this.value;
  51876. case ValueCondition.IsLesser:
  51877. return this._effectiveTarget[this._property] < this.value;
  51878. case ValueCondition.IsEqual:
  51879. case ValueCondition.IsDifferent:
  51880. var check;
  51881. if (this.value.equals) {
  51882. check = this.value.equals(this._effectiveTarget[this._property]);
  51883. }
  51884. else {
  51885. check = this.value === this._effectiveTarget[this._property];
  51886. }
  51887. return this.operator === ValueCondition.IsEqual ? check : !check;
  51888. }
  51889. return false;
  51890. };
  51891. /**
  51892. * Serialize the ValueCondition into a JSON compatible object
  51893. * @returns serialization object
  51894. */
  51895. ValueCondition.prototype.serialize = function () {
  51896. return this._serialize({
  51897. name: "ValueCondition",
  51898. properties: [
  51899. BABYLON.Action._GetTargetProperty(this._target),
  51900. { name: "propertyPath", value: this.propertyPath },
  51901. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51902. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51903. ]
  51904. });
  51905. };
  51906. /**
  51907. * Gets the name of the conditional operator for the ValueCondition
  51908. * @param operator the conditional operator
  51909. * @returns the name
  51910. */
  51911. ValueCondition.GetOperatorName = function (operator) {
  51912. switch (operator) {
  51913. case ValueCondition._IsEqual: return "IsEqual";
  51914. case ValueCondition._IsDifferent: return "IsDifferent";
  51915. case ValueCondition._IsGreater: return "IsGreater";
  51916. case ValueCondition._IsLesser: return "IsLesser";
  51917. default: return "";
  51918. }
  51919. };
  51920. /**
  51921. * Internal only
  51922. * @hidden
  51923. */
  51924. ValueCondition._IsEqual = 0;
  51925. /**
  51926. * Internal only
  51927. * @hidden
  51928. */
  51929. ValueCondition._IsDifferent = 1;
  51930. /**
  51931. * Internal only
  51932. * @hidden
  51933. */
  51934. ValueCondition._IsGreater = 2;
  51935. /**
  51936. * Internal only
  51937. * @hidden
  51938. */
  51939. ValueCondition._IsLesser = 3;
  51940. return ValueCondition;
  51941. }(Condition));
  51942. BABYLON.ValueCondition = ValueCondition;
  51943. /**
  51944. * Defines a predicate condition as an extension of Condition
  51945. */
  51946. var PredicateCondition = /** @class */ (function (_super) {
  51947. __extends(PredicateCondition, _super);
  51948. /**
  51949. * Creates a new PredicateCondition
  51950. * @param actionManager manager for the action the condition applies to
  51951. * @param predicate defines the predicate function used to validate the condition
  51952. */
  51953. function PredicateCondition(actionManager,
  51954. /** defines the predicate function used to validate the condition */
  51955. predicate) {
  51956. var _this = _super.call(this, actionManager) || this;
  51957. _this.predicate = predicate;
  51958. return _this;
  51959. }
  51960. /**
  51961. * @returns the validity of the predicate condition
  51962. */
  51963. PredicateCondition.prototype.isValid = function () {
  51964. return this.predicate();
  51965. };
  51966. return PredicateCondition;
  51967. }(Condition));
  51968. BABYLON.PredicateCondition = PredicateCondition;
  51969. /**
  51970. * Defines a state condition as an extension of Condition
  51971. */
  51972. var StateCondition = /** @class */ (function (_super) {
  51973. __extends(StateCondition, _super);
  51974. /**
  51975. * Creates a new StateCondition
  51976. * @param actionManager manager for the action the condition applies to
  51977. * @param target of the condition
  51978. * @param value to compare with target state
  51979. */
  51980. function StateCondition(actionManager, target, value) {
  51981. var _this = _super.call(this, actionManager) || this;
  51982. _this.value = value;
  51983. _this._target = target;
  51984. return _this;
  51985. }
  51986. /**
  51987. * @returns the validity of the state
  51988. */
  51989. StateCondition.prototype.isValid = function () {
  51990. return this._target.state === this.value;
  51991. };
  51992. /**
  51993. * Serialize the StateCondition into a JSON compatible object
  51994. * @returns serialization object
  51995. */
  51996. StateCondition.prototype.serialize = function () {
  51997. return this._serialize({
  51998. name: "StateCondition",
  51999. properties: [
  52000. BABYLON.Action._GetTargetProperty(this._target),
  52001. { name: "value", value: this.value }
  52002. ]
  52003. });
  52004. };
  52005. return StateCondition;
  52006. }(Condition));
  52007. BABYLON.StateCondition = StateCondition;
  52008. })(BABYLON || (BABYLON = {}));
  52009. //# sourceMappingURL=babylon.condition.js.map
  52010. var BABYLON;
  52011. (function (BABYLON) {
  52012. /**
  52013. * The action to be carried out following a trigger
  52014. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52015. */
  52016. var Action = /** @class */ (function () {
  52017. /**
  52018. * Creates a new Action
  52019. * @param triggerOptions the trigger, with or without parameters, for the action
  52020. * @param condition an optional determinant of action
  52021. */
  52022. function Action(
  52023. /** the trigger, with or without parameters, for the action */
  52024. triggerOptions, condition) {
  52025. this.triggerOptions = triggerOptions;
  52026. /**
  52027. * An event triggered prior to action being executed.
  52028. */
  52029. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52030. if (triggerOptions.parameter) {
  52031. this.trigger = triggerOptions.trigger;
  52032. this._triggerParameter = triggerOptions.parameter;
  52033. }
  52034. else {
  52035. this.trigger = triggerOptions;
  52036. }
  52037. this._nextActiveAction = this;
  52038. this._condition = condition;
  52039. }
  52040. /**
  52041. * Internal only
  52042. * @hidden
  52043. */
  52044. Action.prototype._prepare = function () {
  52045. };
  52046. /**
  52047. * Gets the trigger parameters
  52048. * @returns the trigger parameters
  52049. */
  52050. Action.prototype.getTriggerParameter = function () {
  52051. return this._triggerParameter;
  52052. };
  52053. /**
  52054. * Internal only - executes current action event
  52055. * @hidden
  52056. */
  52057. Action.prototype._executeCurrent = function (evt) {
  52058. if (this._nextActiveAction._condition) {
  52059. var condition = this._nextActiveAction._condition;
  52060. var currentRenderId = this._actionManager.getScene().getRenderId();
  52061. // We cache the current evaluation for the current frame
  52062. if (condition._evaluationId === currentRenderId) {
  52063. if (!condition._currentResult) {
  52064. return;
  52065. }
  52066. }
  52067. else {
  52068. condition._evaluationId = currentRenderId;
  52069. if (!condition.isValid()) {
  52070. condition._currentResult = false;
  52071. return;
  52072. }
  52073. condition._currentResult = true;
  52074. }
  52075. }
  52076. this.onBeforeExecuteObservable.notifyObservers(this);
  52077. this._nextActiveAction.execute(evt);
  52078. this.skipToNextActiveAction();
  52079. };
  52080. /**
  52081. * Execute placeholder for child classes
  52082. * @param evt optional action event
  52083. */
  52084. Action.prototype.execute = function (evt) {
  52085. };
  52086. /**
  52087. * Skips to next active action
  52088. */
  52089. Action.prototype.skipToNextActiveAction = function () {
  52090. if (this._nextActiveAction._child) {
  52091. if (!this._nextActiveAction._child._actionManager) {
  52092. this._nextActiveAction._child._actionManager = this._actionManager;
  52093. }
  52094. this._nextActiveAction = this._nextActiveAction._child;
  52095. }
  52096. else {
  52097. this._nextActiveAction = this;
  52098. }
  52099. };
  52100. /**
  52101. * Adds action to chain of actions, may be a DoNothingAction
  52102. * @param action defines the next action to execute
  52103. * @returns The action passed in
  52104. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52105. */
  52106. Action.prototype.then = function (action) {
  52107. this._child = action;
  52108. action._actionManager = this._actionManager;
  52109. action._prepare();
  52110. return action;
  52111. };
  52112. /**
  52113. * Internal only
  52114. * @hidden
  52115. */
  52116. Action.prototype._getProperty = function (propertyPath) {
  52117. return this._actionManager._getProperty(propertyPath);
  52118. };
  52119. /**
  52120. * Internal only
  52121. * @hidden
  52122. */
  52123. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52124. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52125. };
  52126. /**
  52127. * Serialize placeholder for child classes
  52128. * @param parent of child
  52129. * @returns the serialized object
  52130. */
  52131. Action.prototype.serialize = function (parent) {
  52132. };
  52133. /**
  52134. * Internal only called by serialize
  52135. * @hidden
  52136. */
  52137. Action.prototype._serialize = function (serializedAction, parent) {
  52138. var serializationObject = {
  52139. type: 1,
  52140. children: [],
  52141. name: serializedAction.name,
  52142. properties: serializedAction.properties || []
  52143. };
  52144. // Serialize child
  52145. if (this._child) {
  52146. this._child.serialize(serializationObject);
  52147. }
  52148. // Check if "this" has a condition
  52149. if (this._condition) {
  52150. var serializedCondition = this._condition.serialize();
  52151. serializedCondition.children.push(serializationObject);
  52152. if (parent) {
  52153. parent.children.push(serializedCondition);
  52154. }
  52155. return serializedCondition;
  52156. }
  52157. if (parent) {
  52158. parent.children.push(serializationObject);
  52159. }
  52160. return serializationObject;
  52161. };
  52162. /**
  52163. * Internal only
  52164. * @hidden
  52165. */
  52166. Action._SerializeValueAsString = function (value) {
  52167. if (typeof value === "number") {
  52168. return value.toString();
  52169. }
  52170. if (typeof value === "boolean") {
  52171. return value ? "true" : "false";
  52172. }
  52173. if (value instanceof BABYLON.Vector2) {
  52174. return value.x + ", " + value.y;
  52175. }
  52176. if (value instanceof BABYLON.Vector3) {
  52177. return value.x + ", " + value.y + ", " + value.z;
  52178. }
  52179. if (value instanceof BABYLON.Color3) {
  52180. return value.r + ", " + value.g + ", " + value.b;
  52181. }
  52182. if (value instanceof BABYLON.Color4) {
  52183. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52184. }
  52185. return value; // string
  52186. };
  52187. /**
  52188. * Internal only
  52189. * @hidden
  52190. */
  52191. Action._GetTargetProperty = function (target) {
  52192. return {
  52193. name: "target",
  52194. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52195. : target instanceof BABYLON.Light ? "LightProperties"
  52196. : target instanceof BABYLON.Camera ? "CameraProperties"
  52197. : "SceneProperties",
  52198. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52199. };
  52200. };
  52201. return Action;
  52202. }());
  52203. BABYLON.Action = Action;
  52204. })(BABYLON || (BABYLON = {}));
  52205. //# sourceMappingURL=babylon.action.js.map
  52206. var BABYLON;
  52207. (function (BABYLON) {
  52208. /**
  52209. * ActionEvent is the event being sent when an action is triggered.
  52210. */
  52211. var ActionEvent = /** @class */ (function () {
  52212. /**
  52213. * Creates a new ActionEvent
  52214. * @param source The mesh or sprite that triggered the action
  52215. * @param pointerX The X mouse cursor position at the time of the event
  52216. * @param pointerY The Y mouse cursor position at the time of the event
  52217. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52218. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52219. * @param additionalData additional data for the event
  52220. */
  52221. function ActionEvent(
  52222. /** The mesh or sprite that triggered the action */
  52223. source,
  52224. /** The X mouse cursor position at the time of the event */
  52225. pointerX,
  52226. /** The Y mouse cursor position at the time of the event */
  52227. pointerY,
  52228. /** The mesh that is currently pointed at (can be null) */
  52229. meshUnderPointer,
  52230. /** the original (browser) event that triggered the ActionEvent */
  52231. sourceEvent,
  52232. /** additional data for the event */
  52233. additionalData) {
  52234. this.source = source;
  52235. this.pointerX = pointerX;
  52236. this.pointerY = pointerY;
  52237. this.meshUnderPointer = meshUnderPointer;
  52238. this.sourceEvent = sourceEvent;
  52239. this.additionalData = additionalData;
  52240. }
  52241. /**
  52242. * Helper function to auto-create an ActionEvent from a source mesh.
  52243. * @param source The source mesh that triggered the event
  52244. * @param evt The original (browser) event
  52245. * @param additionalData additional data for the event
  52246. * @returns the new ActionEvent
  52247. */
  52248. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52249. var scene = source.getScene();
  52250. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52251. };
  52252. /**
  52253. * Helper function to auto-create an ActionEvent from a source sprite
  52254. * @param source The source sprite that triggered the event
  52255. * @param scene Scene associated with the sprite
  52256. * @param evt The original (browser) event
  52257. * @param additionalData additional data for the event
  52258. * @returns the new ActionEvent
  52259. */
  52260. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52261. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52262. };
  52263. /**
  52264. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52265. * @param scene the scene where the event occurred
  52266. * @param evt The original (browser) event
  52267. * @returns the new ActionEvent
  52268. */
  52269. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52270. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52271. };
  52272. /**
  52273. * Helper function to auto-create an ActionEvent from a primitive
  52274. * @param prim defines the target primitive
  52275. * @param pointerPos defines the pointer position
  52276. * @param evt The original (browser) event
  52277. * @param additionalData additional data for the event
  52278. * @returns the new ActionEvent
  52279. */
  52280. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52281. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52282. };
  52283. return ActionEvent;
  52284. }());
  52285. BABYLON.ActionEvent = ActionEvent;
  52286. /**
  52287. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52288. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52289. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52290. */
  52291. var ActionManager = /** @class */ (function () {
  52292. /**
  52293. * Creates a new action manager
  52294. * @param scene defines the hosting scene
  52295. */
  52296. function ActionManager(scene) {
  52297. // Members
  52298. /** Gets the list of actions */
  52299. this.actions = new Array();
  52300. /** Gets the cursor to use when hovering items */
  52301. this.hoverCursor = '';
  52302. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52303. scene._actionManagers.push(this);
  52304. }
  52305. Object.defineProperty(ActionManager, "NothingTrigger", {
  52306. /**
  52307. * Nothing
  52308. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52309. */
  52310. get: function () {
  52311. return ActionManager._NothingTrigger;
  52312. },
  52313. enumerable: true,
  52314. configurable: true
  52315. });
  52316. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52317. /**
  52318. * On pick
  52319. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52320. */
  52321. get: function () {
  52322. return ActionManager._OnPickTrigger;
  52323. },
  52324. enumerable: true,
  52325. configurable: true
  52326. });
  52327. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52328. /**
  52329. * On left pick
  52330. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52331. */
  52332. get: function () {
  52333. return ActionManager._OnLeftPickTrigger;
  52334. },
  52335. enumerable: true,
  52336. configurable: true
  52337. });
  52338. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52339. /**
  52340. * On right pick
  52341. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52342. */
  52343. get: function () {
  52344. return ActionManager._OnRightPickTrigger;
  52345. },
  52346. enumerable: true,
  52347. configurable: true
  52348. });
  52349. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52350. /**
  52351. * On center pick
  52352. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52353. */
  52354. get: function () {
  52355. return ActionManager._OnCenterPickTrigger;
  52356. },
  52357. enumerable: true,
  52358. configurable: true
  52359. });
  52360. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52361. /**
  52362. * On pick down
  52363. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52364. */
  52365. get: function () {
  52366. return ActionManager._OnPickDownTrigger;
  52367. },
  52368. enumerable: true,
  52369. configurable: true
  52370. });
  52371. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52372. /**
  52373. * On double pick
  52374. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52375. */
  52376. get: function () {
  52377. return ActionManager._OnDoublePickTrigger;
  52378. },
  52379. enumerable: true,
  52380. configurable: true
  52381. });
  52382. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52383. /**
  52384. * On pick up
  52385. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52386. */
  52387. get: function () {
  52388. return ActionManager._OnPickUpTrigger;
  52389. },
  52390. enumerable: true,
  52391. configurable: true
  52392. });
  52393. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52394. /**
  52395. * On pick out.
  52396. * This trigger will only be raised if you also declared a OnPickDown
  52397. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52398. */
  52399. get: function () {
  52400. return ActionManager._OnPickOutTrigger;
  52401. },
  52402. enumerable: true,
  52403. configurable: true
  52404. });
  52405. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52406. /**
  52407. * On long press
  52408. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52409. */
  52410. get: function () {
  52411. return ActionManager._OnLongPressTrigger;
  52412. },
  52413. enumerable: true,
  52414. configurable: true
  52415. });
  52416. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52417. /**
  52418. * On pointer over
  52419. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52420. */
  52421. get: function () {
  52422. return ActionManager._OnPointerOverTrigger;
  52423. },
  52424. enumerable: true,
  52425. configurable: true
  52426. });
  52427. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52428. /**
  52429. * On pointer out
  52430. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52431. */
  52432. get: function () {
  52433. return ActionManager._OnPointerOutTrigger;
  52434. },
  52435. enumerable: true,
  52436. configurable: true
  52437. });
  52438. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52439. /**
  52440. * On every frame
  52441. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52442. */
  52443. get: function () {
  52444. return ActionManager._OnEveryFrameTrigger;
  52445. },
  52446. enumerable: true,
  52447. configurable: true
  52448. });
  52449. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52450. /**
  52451. * On intersection enter
  52452. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52453. */
  52454. get: function () {
  52455. return ActionManager._OnIntersectionEnterTrigger;
  52456. },
  52457. enumerable: true,
  52458. configurable: true
  52459. });
  52460. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52461. /**
  52462. * On intersection exit
  52463. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52464. */
  52465. get: function () {
  52466. return ActionManager._OnIntersectionExitTrigger;
  52467. },
  52468. enumerable: true,
  52469. configurable: true
  52470. });
  52471. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52472. /**
  52473. * On key down
  52474. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52475. */
  52476. get: function () {
  52477. return ActionManager._OnKeyDownTrigger;
  52478. },
  52479. enumerable: true,
  52480. configurable: true
  52481. });
  52482. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52483. /**
  52484. * On key up
  52485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52486. */
  52487. get: function () {
  52488. return ActionManager._OnKeyUpTrigger;
  52489. },
  52490. enumerable: true,
  52491. configurable: true
  52492. });
  52493. // Methods
  52494. /**
  52495. * Releases all associated resources
  52496. */
  52497. ActionManager.prototype.dispose = function () {
  52498. var index = this._scene._actionManagers.indexOf(this);
  52499. for (var i = 0; i < this.actions.length; i++) {
  52500. var action = this.actions[i];
  52501. ActionManager.Triggers[action.trigger]--;
  52502. if (ActionManager.Triggers[action.trigger] === 0) {
  52503. delete ActionManager.Triggers[action.trigger];
  52504. }
  52505. }
  52506. if (index > -1) {
  52507. this._scene._actionManagers.splice(index, 1);
  52508. }
  52509. };
  52510. /**
  52511. * Gets hosting scene
  52512. * @returns the hosting scene
  52513. */
  52514. ActionManager.prototype.getScene = function () {
  52515. return this._scene;
  52516. };
  52517. /**
  52518. * Does this action manager handles actions of any of the given triggers
  52519. * @param triggers defines the triggers to be tested
  52520. * @return a boolean indicating whether one (or more) of the triggers is handled
  52521. */
  52522. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52523. for (var index = 0; index < this.actions.length; index++) {
  52524. var action = this.actions[index];
  52525. if (triggers.indexOf(action.trigger) > -1) {
  52526. return true;
  52527. }
  52528. }
  52529. return false;
  52530. };
  52531. /**
  52532. * Does this action manager handles actions of a given trigger
  52533. * @param trigger defines the trigger to be tested
  52534. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52535. * @return whether the trigger is handled
  52536. */
  52537. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52538. for (var index = 0; index < this.actions.length; index++) {
  52539. var action = this.actions[index];
  52540. if (action.trigger === trigger) {
  52541. if (parameterPredicate) {
  52542. if (parameterPredicate(action.getTriggerParameter())) {
  52543. return true;
  52544. }
  52545. }
  52546. else {
  52547. return true;
  52548. }
  52549. }
  52550. }
  52551. return false;
  52552. };
  52553. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52554. /**
  52555. * Does this action manager has pointer triggers
  52556. */
  52557. get: function () {
  52558. for (var index = 0; index < this.actions.length; index++) {
  52559. var action = this.actions[index];
  52560. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52561. return true;
  52562. }
  52563. }
  52564. return false;
  52565. },
  52566. enumerable: true,
  52567. configurable: true
  52568. });
  52569. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52570. /**
  52571. * Does this action manager has pick triggers
  52572. */
  52573. get: function () {
  52574. for (var index = 0; index < this.actions.length; index++) {
  52575. var action = this.actions[index];
  52576. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52577. return true;
  52578. }
  52579. }
  52580. return false;
  52581. },
  52582. enumerable: true,
  52583. configurable: true
  52584. });
  52585. Object.defineProperty(ActionManager, "HasTriggers", {
  52586. /**
  52587. * Does exist one action manager with at least one trigger
  52588. **/
  52589. get: function () {
  52590. for (var t in ActionManager.Triggers) {
  52591. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52592. return true;
  52593. }
  52594. }
  52595. return false;
  52596. },
  52597. enumerable: true,
  52598. configurable: true
  52599. });
  52600. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52601. /**
  52602. * Does exist one action manager with at least one pick trigger
  52603. **/
  52604. get: function () {
  52605. for (var t in ActionManager.Triggers) {
  52606. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52607. var t_int = parseInt(t);
  52608. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52609. return true;
  52610. }
  52611. }
  52612. }
  52613. return false;
  52614. },
  52615. enumerable: true,
  52616. configurable: true
  52617. });
  52618. /**
  52619. * Does exist one action manager that handles actions of a given trigger
  52620. * @param trigger defines the trigger to be tested
  52621. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52622. **/
  52623. ActionManager.HasSpecificTrigger = function (trigger) {
  52624. for (var t in ActionManager.Triggers) {
  52625. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52626. var t_int = parseInt(t);
  52627. if (t_int === trigger) {
  52628. return true;
  52629. }
  52630. }
  52631. }
  52632. return false;
  52633. };
  52634. /**
  52635. * Registers an action to this action manager
  52636. * @param action defines the action to be registered
  52637. * @return the action amended (prepared) after registration
  52638. */
  52639. ActionManager.prototype.registerAction = function (action) {
  52640. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52641. if (this.getScene().actionManager !== this) {
  52642. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52643. return null;
  52644. }
  52645. }
  52646. this.actions.push(action);
  52647. if (ActionManager.Triggers[action.trigger]) {
  52648. ActionManager.Triggers[action.trigger]++;
  52649. }
  52650. else {
  52651. ActionManager.Triggers[action.trigger] = 1;
  52652. }
  52653. action._actionManager = this;
  52654. action._prepare();
  52655. return action;
  52656. };
  52657. /**
  52658. * Unregisters an action to this action manager
  52659. * @param action defines the action to be unregistered
  52660. * @return a boolean indicating whether the action has been unregistered
  52661. */
  52662. ActionManager.prototype.unregisterAction = function (action) {
  52663. var index = this.actions.indexOf(action);
  52664. if (index !== -1) {
  52665. this.actions.splice(index, 1);
  52666. ActionManager.Triggers[action.trigger] -= 1;
  52667. if (ActionManager.Triggers[action.trigger] === 0) {
  52668. delete ActionManager.Triggers[action.trigger];
  52669. }
  52670. delete action._actionManager;
  52671. return true;
  52672. }
  52673. return false;
  52674. };
  52675. /**
  52676. * Process a specific trigger
  52677. * @param trigger defines the trigger to process
  52678. * @param evt defines the event details to be processed
  52679. */
  52680. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52681. for (var index = 0; index < this.actions.length; index++) {
  52682. var action = this.actions[index];
  52683. if (action.trigger === trigger) {
  52684. if (evt) {
  52685. if (trigger === ActionManager.OnKeyUpTrigger
  52686. || trigger === ActionManager.OnKeyDownTrigger) {
  52687. var parameter = action.getTriggerParameter();
  52688. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52689. if (!parameter.toLowerCase) {
  52690. continue;
  52691. }
  52692. var lowerCase = parameter.toLowerCase();
  52693. if (lowerCase !== evt.sourceEvent.key) {
  52694. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52695. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52696. if (actualkey !== lowerCase) {
  52697. continue;
  52698. }
  52699. }
  52700. }
  52701. }
  52702. }
  52703. action._executeCurrent(evt);
  52704. }
  52705. }
  52706. };
  52707. /** @hidden */
  52708. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52709. var properties = propertyPath.split(".");
  52710. for (var index = 0; index < properties.length - 1; index++) {
  52711. target = target[properties[index]];
  52712. }
  52713. return target;
  52714. };
  52715. /** @hidden */
  52716. ActionManager.prototype._getProperty = function (propertyPath) {
  52717. var properties = propertyPath.split(".");
  52718. return properties[properties.length - 1];
  52719. };
  52720. /**
  52721. * Serialize this manager to a JSON object
  52722. * @param name defines the property name to store this manager
  52723. * @returns a JSON representation of this manager
  52724. */
  52725. ActionManager.prototype.serialize = function (name) {
  52726. var root = {
  52727. children: new Array(),
  52728. name: name,
  52729. type: 3,
  52730. properties: new Array() // Empty for root but required
  52731. };
  52732. for (var i = 0; i < this.actions.length; i++) {
  52733. var triggerObject = {
  52734. type: 0,
  52735. children: new Array(),
  52736. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52737. properties: new Array()
  52738. };
  52739. var triggerOptions = this.actions[i].triggerOptions;
  52740. if (triggerOptions && typeof triggerOptions !== "number") {
  52741. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52742. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52743. }
  52744. else {
  52745. var parameter = {};
  52746. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52747. if (triggerOptions.parameter.mesh) {
  52748. parameter._meshId = triggerOptions.parameter.mesh.id;
  52749. }
  52750. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52751. }
  52752. }
  52753. // Serialize child action, recursively
  52754. this.actions[i].serialize(triggerObject);
  52755. // Add serialized trigger
  52756. root.children.push(triggerObject);
  52757. }
  52758. return root;
  52759. };
  52760. /**
  52761. * Creates a new ActionManager from a JSON data
  52762. * @param parsedActions defines the JSON data to read from
  52763. * @param object defines the hosting mesh
  52764. * @param scene defines the hosting scene
  52765. */
  52766. ActionManager.Parse = function (parsedActions, object, scene) {
  52767. var actionManager = new ActionManager(scene);
  52768. if (object === null)
  52769. scene.actionManager = actionManager;
  52770. else
  52771. object.actionManager = actionManager;
  52772. // instanciate a new object
  52773. var instanciate = function (name, params) {
  52774. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52775. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52776. newInstance.constructor.apply(newInstance, params);
  52777. return newInstance;
  52778. };
  52779. var parseParameter = function (name, value, target, propertyPath) {
  52780. if (propertyPath === null) {
  52781. // String, boolean or float
  52782. var floatValue = parseFloat(value);
  52783. if (value === "true" || value === "false")
  52784. return value === "true";
  52785. else
  52786. return isNaN(floatValue) ? value : floatValue;
  52787. }
  52788. var effectiveTarget = propertyPath.split(".");
  52789. var values = value.split(",");
  52790. // Get effective Target
  52791. for (var i = 0; i < effectiveTarget.length; i++) {
  52792. target = target[effectiveTarget[i]];
  52793. }
  52794. // Return appropriate value with its type
  52795. if (typeof (target) === "boolean")
  52796. return values[0] === "true";
  52797. if (typeof (target) === "string")
  52798. return values[0];
  52799. // Parameters with multiple values such as Vector3 etc.
  52800. var split = new Array();
  52801. for (var i = 0; i < values.length; i++)
  52802. split.push(parseFloat(values[i]));
  52803. if (target instanceof BABYLON.Vector3)
  52804. return BABYLON.Vector3.FromArray(split);
  52805. if (target instanceof BABYLON.Vector4)
  52806. return BABYLON.Vector4.FromArray(split);
  52807. if (target instanceof BABYLON.Color3)
  52808. return BABYLON.Color3.FromArray(split);
  52809. if (target instanceof BABYLON.Color4)
  52810. return BABYLON.Color4.FromArray(split);
  52811. return parseFloat(values[0]);
  52812. };
  52813. // traverse graph per trigger
  52814. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52815. if (combineArray === void 0) { combineArray = null; }
  52816. if (parsedAction.detached)
  52817. return;
  52818. var parameters = new Array();
  52819. var target = null;
  52820. var propertyPath = null;
  52821. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52822. // Parameters
  52823. if (parsedAction.type === 2)
  52824. parameters.push(actionManager);
  52825. else
  52826. parameters.push(trigger);
  52827. if (combine) {
  52828. var actions = new Array();
  52829. for (var j = 0; j < parsedAction.combine.length; j++) {
  52830. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52831. }
  52832. parameters.push(actions);
  52833. }
  52834. else {
  52835. for (var i = 0; i < parsedAction.properties.length; i++) {
  52836. var value = parsedAction.properties[i].value;
  52837. var name = parsedAction.properties[i].name;
  52838. var targetType = parsedAction.properties[i].targetType;
  52839. if (name === "target")
  52840. if (targetType !== null && targetType === "SceneProperties")
  52841. value = target = scene;
  52842. else
  52843. value = target = scene.getNodeByName(value);
  52844. else if (name === "parent")
  52845. value = scene.getNodeByName(value);
  52846. else if (name === "sound")
  52847. value = scene.getSoundByName(value);
  52848. else if (name !== "propertyPath") {
  52849. if (parsedAction.type === 2 && name === "operator")
  52850. value = BABYLON.ValueCondition[value];
  52851. else
  52852. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52853. }
  52854. else {
  52855. propertyPath = value;
  52856. }
  52857. parameters.push(value);
  52858. }
  52859. }
  52860. if (combineArray === null) {
  52861. parameters.push(condition);
  52862. }
  52863. else {
  52864. parameters.push(null);
  52865. }
  52866. // If interpolate value action
  52867. if (parsedAction.name === "InterpolateValueAction") {
  52868. var param = parameters[parameters.length - 2];
  52869. parameters[parameters.length - 1] = param;
  52870. parameters[parameters.length - 2] = condition;
  52871. }
  52872. // Action or condition(s) and not CombineAction
  52873. var newAction = instanciate(parsedAction.name, parameters);
  52874. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52875. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52876. if (action)
  52877. action.then(nothing);
  52878. else
  52879. actionManager.registerAction(nothing);
  52880. action = nothing;
  52881. }
  52882. if (combineArray === null) {
  52883. if (newAction instanceof BABYLON.Condition) {
  52884. condition = newAction;
  52885. newAction = action;
  52886. }
  52887. else {
  52888. condition = null;
  52889. if (action)
  52890. action.then(newAction);
  52891. else
  52892. actionManager.registerAction(newAction);
  52893. }
  52894. }
  52895. else {
  52896. combineArray.push(newAction);
  52897. }
  52898. for (var i = 0; i < parsedAction.children.length; i++)
  52899. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52900. };
  52901. // triggers
  52902. for (var i = 0; i < parsedActions.children.length; i++) {
  52903. var triggerParams;
  52904. var trigger = parsedActions.children[i];
  52905. if (trigger.properties.length > 0) {
  52906. var param = trigger.properties[0].value;
  52907. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52908. if (value._meshId) {
  52909. value.mesh = scene.getMeshByID(value._meshId);
  52910. }
  52911. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  52912. }
  52913. else
  52914. triggerParams = ActionManager[trigger.name];
  52915. for (var j = 0; j < trigger.children.length; j++) {
  52916. if (!trigger.detached)
  52917. traverse(trigger.children[j], triggerParams, null, null);
  52918. }
  52919. }
  52920. };
  52921. /**
  52922. * Get a trigger name by index
  52923. * @param trigger defines the trigger index
  52924. * @returns a trigger name
  52925. */
  52926. ActionManager.GetTriggerName = function (trigger) {
  52927. switch (trigger) {
  52928. case 0: return "NothingTrigger";
  52929. case 1: return "OnPickTrigger";
  52930. case 2: return "OnLeftPickTrigger";
  52931. case 3: return "OnRightPickTrigger";
  52932. case 4: return "OnCenterPickTrigger";
  52933. case 5: return "OnPickDownTrigger";
  52934. case 6: return "OnPickUpTrigger";
  52935. case 7: return "OnLongPressTrigger";
  52936. case 8: return "OnPointerOverTrigger";
  52937. case 9: return "OnPointerOutTrigger";
  52938. case 10: return "OnEveryFrameTrigger";
  52939. case 11: return "OnIntersectionEnterTrigger";
  52940. case 12: return "OnIntersectionExitTrigger";
  52941. case 13: return "OnKeyDownTrigger";
  52942. case 14: return "OnKeyUpTrigger";
  52943. case 15: return "OnPickOutTrigger";
  52944. default: return "";
  52945. }
  52946. };
  52947. // Statics
  52948. ActionManager._NothingTrigger = 0;
  52949. ActionManager._OnPickTrigger = 1;
  52950. ActionManager._OnLeftPickTrigger = 2;
  52951. ActionManager._OnRightPickTrigger = 3;
  52952. ActionManager._OnCenterPickTrigger = 4;
  52953. ActionManager._OnPickDownTrigger = 5;
  52954. ActionManager._OnDoublePickTrigger = 6;
  52955. ActionManager._OnPickUpTrigger = 7;
  52956. ActionManager._OnLongPressTrigger = 8;
  52957. ActionManager._OnPointerOverTrigger = 9;
  52958. ActionManager._OnPointerOutTrigger = 10;
  52959. ActionManager._OnEveryFrameTrigger = 11;
  52960. ActionManager._OnIntersectionEnterTrigger = 12;
  52961. ActionManager._OnIntersectionExitTrigger = 13;
  52962. ActionManager._OnKeyDownTrigger = 14;
  52963. ActionManager._OnKeyUpTrigger = 15;
  52964. ActionManager._OnPickOutTrigger = 16;
  52965. /** Gets the list of active triggers */
  52966. ActionManager.Triggers = {};
  52967. return ActionManager;
  52968. }());
  52969. BABYLON.ActionManager = ActionManager;
  52970. })(BABYLON || (BABYLON = {}));
  52971. //# sourceMappingURL=babylon.actionManager.js.map
  52972. var BABYLON;
  52973. (function (BABYLON) {
  52974. var InterpolateValueAction = /** @class */ (function (_super) {
  52975. __extends(InterpolateValueAction, _super);
  52976. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  52977. if (duration === void 0) { duration = 1000; }
  52978. var _this = _super.call(this, triggerOptions, condition) || this;
  52979. _this.propertyPath = propertyPath;
  52980. _this.value = value;
  52981. _this.duration = duration;
  52982. _this.stopOtherAnimations = stopOtherAnimations;
  52983. _this.onInterpolationDone = onInterpolationDone;
  52984. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  52985. _this._target = _this._effectiveTarget = target;
  52986. return _this;
  52987. }
  52988. InterpolateValueAction.prototype._prepare = function () {
  52989. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  52990. this._property = this._getProperty(this.propertyPath);
  52991. };
  52992. InterpolateValueAction.prototype.execute = function () {
  52993. var _this = this;
  52994. var scene = this._actionManager.getScene();
  52995. var keys = [
  52996. {
  52997. frame: 0,
  52998. value: this._effectiveTarget[this._property]
  52999. }, {
  53000. frame: 100,
  53001. value: this.value
  53002. }
  53003. ];
  53004. var dataType;
  53005. if (typeof this.value === "number") {
  53006. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53007. }
  53008. else if (this.value instanceof BABYLON.Color3) {
  53009. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53010. }
  53011. else if (this.value instanceof BABYLON.Vector3) {
  53012. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53013. }
  53014. else if (this.value instanceof BABYLON.Matrix) {
  53015. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53016. }
  53017. else if (this.value instanceof BABYLON.Quaternion) {
  53018. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53019. }
  53020. else {
  53021. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53022. return;
  53023. }
  53024. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53025. animation.setKeys(keys);
  53026. if (this.stopOtherAnimations) {
  53027. scene.stopAnimation(this._effectiveTarget);
  53028. }
  53029. var wrapper = function () {
  53030. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53031. if (_this.onInterpolationDone) {
  53032. _this.onInterpolationDone();
  53033. }
  53034. };
  53035. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53036. };
  53037. InterpolateValueAction.prototype.serialize = function (parent) {
  53038. return _super.prototype._serialize.call(this, {
  53039. name: "InterpolateValueAction",
  53040. properties: [
  53041. BABYLON.Action._GetTargetProperty(this._target),
  53042. { name: "propertyPath", value: this.propertyPath },
  53043. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53044. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53045. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53046. ]
  53047. }, parent);
  53048. };
  53049. return InterpolateValueAction;
  53050. }(BABYLON.Action));
  53051. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53052. })(BABYLON || (BABYLON = {}));
  53053. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53054. var BABYLON;
  53055. (function (BABYLON) {
  53056. var SwitchBooleanAction = /** @class */ (function (_super) {
  53057. __extends(SwitchBooleanAction, _super);
  53058. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53059. var _this = _super.call(this, triggerOptions, condition) || this;
  53060. _this.propertyPath = propertyPath;
  53061. _this._target = _this._effectiveTarget = target;
  53062. return _this;
  53063. }
  53064. SwitchBooleanAction.prototype._prepare = function () {
  53065. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53066. this._property = this._getProperty(this.propertyPath);
  53067. };
  53068. SwitchBooleanAction.prototype.execute = function () {
  53069. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53070. };
  53071. SwitchBooleanAction.prototype.serialize = function (parent) {
  53072. return _super.prototype._serialize.call(this, {
  53073. name: "SwitchBooleanAction",
  53074. properties: [
  53075. BABYLON.Action._GetTargetProperty(this._target),
  53076. { name: "propertyPath", value: this.propertyPath }
  53077. ]
  53078. }, parent);
  53079. };
  53080. return SwitchBooleanAction;
  53081. }(BABYLON.Action));
  53082. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53083. var SetStateAction = /** @class */ (function (_super) {
  53084. __extends(SetStateAction, _super);
  53085. function SetStateAction(triggerOptions, target, value, condition) {
  53086. var _this = _super.call(this, triggerOptions, condition) || this;
  53087. _this.value = value;
  53088. _this._target = target;
  53089. return _this;
  53090. }
  53091. SetStateAction.prototype.execute = function () {
  53092. this._target.state = this.value;
  53093. };
  53094. SetStateAction.prototype.serialize = function (parent) {
  53095. return _super.prototype._serialize.call(this, {
  53096. name: "SetStateAction",
  53097. properties: [
  53098. BABYLON.Action._GetTargetProperty(this._target),
  53099. { name: "value", value: this.value }
  53100. ]
  53101. }, parent);
  53102. };
  53103. return SetStateAction;
  53104. }(BABYLON.Action));
  53105. BABYLON.SetStateAction = SetStateAction;
  53106. var SetValueAction = /** @class */ (function (_super) {
  53107. __extends(SetValueAction, _super);
  53108. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53109. var _this = _super.call(this, triggerOptions, condition) || this;
  53110. _this.propertyPath = propertyPath;
  53111. _this.value = value;
  53112. _this._target = _this._effectiveTarget = target;
  53113. return _this;
  53114. }
  53115. SetValueAction.prototype._prepare = function () {
  53116. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53117. this._property = this._getProperty(this.propertyPath);
  53118. };
  53119. SetValueAction.prototype.execute = function () {
  53120. this._effectiveTarget[this._property] = this.value;
  53121. if (this._target.markAsDirty) {
  53122. this._target.markAsDirty(this._property);
  53123. }
  53124. };
  53125. SetValueAction.prototype.serialize = function (parent) {
  53126. return _super.prototype._serialize.call(this, {
  53127. name: "SetValueAction",
  53128. properties: [
  53129. BABYLON.Action._GetTargetProperty(this._target),
  53130. { name: "propertyPath", value: this.propertyPath },
  53131. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53132. ]
  53133. }, parent);
  53134. };
  53135. return SetValueAction;
  53136. }(BABYLON.Action));
  53137. BABYLON.SetValueAction = SetValueAction;
  53138. var IncrementValueAction = /** @class */ (function (_super) {
  53139. __extends(IncrementValueAction, _super);
  53140. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53141. var _this = _super.call(this, triggerOptions, condition) || this;
  53142. _this.propertyPath = propertyPath;
  53143. _this.value = value;
  53144. _this._target = _this._effectiveTarget = target;
  53145. return _this;
  53146. }
  53147. IncrementValueAction.prototype._prepare = function () {
  53148. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53149. this._property = this._getProperty(this.propertyPath);
  53150. if (typeof this._effectiveTarget[this._property] !== "number") {
  53151. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53152. }
  53153. };
  53154. IncrementValueAction.prototype.execute = function () {
  53155. this._effectiveTarget[this._property] += this.value;
  53156. if (this._target.markAsDirty) {
  53157. this._target.markAsDirty(this._property);
  53158. }
  53159. };
  53160. IncrementValueAction.prototype.serialize = function (parent) {
  53161. return _super.prototype._serialize.call(this, {
  53162. name: "IncrementValueAction",
  53163. properties: [
  53164. BABYLON.Action._GetTargetProperty(this._target),
  53165. { name: "propertyPath", value: this.propertyPath },
  53166. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53167. ]
  53168. }, parent);
  53169. };
  53170. return IncrementValueAction;
  53171. }(BABYLON.Action));
  53172. BABYLON.IncrementValueAction = IncrementValueAction;
  53173. var PlayAnimationAction = /** @class */ (function (_super) {
  53174. __extends(PlayAnimationAction, _super);
  53175. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53176. var _this = _super.call(this, triggerOptions, condition) || this;
  53177. _this.from = from;
  53178. _this.to = to;
  53179. _this.loop = loop;
  53180. _this._target = target;
  53181. return _this;
  53182. }
  53183. PlayAnimationAction.prototype._prepare = function () {
  53184. };
  53185. PlayAnimationAction.prototype.execute = function () {
  53186. var scene = this._actionManager.getScene();
  53187. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53188. };
  53189. PlayAnimationAction.prototype.serialize = function (parent) {
  53190. return _super.prototype._serialize.call(this, {
  53191. name: "PlayAnimationAction",
  53192. properties: [
  53193. BABYLON.Action._GetTargetProperty(this._target),
  53194. { name: "from", value: String(this.from) },
  53195. { name: "to", value: String(this.to) },
  53196. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53197. ]
  53198. }, parent);
  53199. };
  53200. return PlayAnimationAction;
  53201. }(BABYLON.Action));
  53202. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53203. var StopAnimationAction = /** @class */ (function (_super) {
  53204. __extends(StopAnimationAction, _super);
  53205. function StopAnimationAction(triggerOptions, target, condition) {
  53206. var _this = _super.call(this, triggerOptions, condition) || this;
  53207. _this._target = target;
  53208. return _this;
  53209. }
  53210. StopAnimationAction.prototype._prepare = function () {
  53211. };
  53212. StopAnimationAction.prototype.execute = function () {
  53213. var scene = this._actionManager.getScene();
  53214. scene.stopAnimation(this._target);
  53215. };
  53216. StopAnimationAction.prototype.serialize = function (parent) {
  53217. return _super.prototype._serialize.call(this, {
  53218. name: "StopAnimationAction",
  53219. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53220. }, parent);
  53221. };
  53222. return StopAnimationAction;
  53223. }(BABYLON.Action));
  53224. BABYLON.StopAnimationAction = StopAnimationAction;
  53225. var DoNothingAction = /** @class */ (function (_super) {
  53226. __extends(DoNothingAction, _super);
  53227. function DoNothingAction(triggerOptions, condition) {
  53228. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53229. return _super.call(this, triggerOptions, condition) || this;
  53230. }
  53231. DoNothingAction.prototype.execute = function () {
  53232. };
  53233. DoNothingAction.prototype.serialize = function (parent) {
  53234. return _super.prototype._serialize.call(this, {
  53235. name: "DoNothingAction",
  53236. properties: []
  53237. }, parent);
  53238. };
  53239. return DoNothingAction;
  53240. }(BABYLON.Action));
  53241. BABYLON.DoNothingAction = DoNothingAction;
  53242. var CombineAction = /** @class */ (function (_super) {
  53243. __extends(CombineAction, _super);
  53244. function CombineAction(triggerOptions, children, condition) {
  53245. var _this = _super.call(this, triggerOptions, condition) || this;
  53246. _this.children = children;
  53247. return _this;
  53248. }
  53249. CombineAction.prototype._prepare = function () {
  53250. for (var index = 0; index < this.children.length; index++) {
  53251. this.children[index]._actionManager = this._actionManager;
  53252. this.children[index]._prepare();
  53253. }
  53254. };
  53255. CombineAction.prototype.execute = function (evt) {
  53256. for (var index = 0; index < this.children.length; index++) {
  53257. this.children[index].execute(evt);
  53258. }
  53259. };
  53260. CombineAction.prototype.serialize = function (parent) {
  53261. var serializationObject = _super.prototype._serialize.call(this, {
  53262. name: "CombineAction",
  53263. properties: [],
  53264. combine: []
  53265. }, parent);
  53266. for (var i = 0; i < this.children.length; i++) {
  53267. serializationObject.combine.push(this.children[i].serialize(null));
  53268. }
  53269. return serializationObject;
  53270. };
  53271. return CombineAction;
  53272. }(BABYLON.Action));
  53273. BABYLON.CombineAction = CombineAction;
  53274. var ExecuteCodeAction = /** @class */ (function (_super) {
  53275. __extends(ExecuteCodeAction, _super);
  53276. function ExecuteCodeAction(triggerOptions, func, condition) {
  53277. var _this = _super.call(this, triggerOptions, condition) || this;
  53278. _this.func = func;
  53279. return _this;
  53280. }
  53281. ExecuteCodeAction.prototype.execute = function (evt) {
  53282. this.func(evt);
  53283. };
  53284. return ExecuteCodeAction;
  53285. }(BABYLON.Action));
  53286. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53287. var SetParentAction = /** @class */ (function (_super) {
  53288. __extends(SetParentAction, _super);
  53289. function SetParentAction(triggerOptions, target, parent, condition) {
  53290. var _this = _super.call(this, triggerOptions, condition) || this;
  53291. _this._target = target;
  53292. _this._parent = parent;
  53293. return _this;
  53294. }
  53295. SetParentAction.prototype._prepare = function () {
  53296. };
  53297. SetParentAction.prototype.execute = function () {
  53298. if (this._target.parent === this._parent) {
  53299. return;
  53300. }
  53301. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53302. invertParentWorldMatrix.invert();
  53303. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53304. this._target.parent = this._parent;
  53305. };
  53306. SetParentAction.prototype.serialize = function (parent) {
  53307. return _super.prototype._serialize.call(this, {
  53308. name: "SetParentAction",
  53309. properties: [
  53310. BABYLON.Action._GetTargetProperty(this._target),
  53311. BABYLON.Action._GetTargetProperty(this._parent),
  53312. ]
  53313. }, parent);
  53314. };
  53315. return SetParentAction;
  53316. }(BABYLON.Action));
  53317. BABYLON.SetParentAction = SetParentAction;
  53318. var PlaySoundAction = /** @class */ (function (_super) {
  53319. __extends(PlaySoundAction, _super);
  53320. function PlaySoundAction(triggerOptions, sound, condition) {
  53321. var _this = _super.call(this, triggerOptions, condition) || this;
  53322. _this._sound = sound;
  53323. return _this;
  53324. }
  53325. PlaySoundAction.prototype._prepare = function () {
  53326. };
  53327. PlaySoundAction.prototype.execute = function () {
  53328. if (this._sound !== undefined)
  53329. this._sound.play();
  53330. };
  53331. PlaySoundAction.prototype.serialize = function (parent) {
  53332. return _super.prototype._serialize.call(this, {
  53333. name: "PlaySoundAction",
  53334. properties: [{ name: "sound", value: this._sound.name }]
  53335. }, parent);
  53336. };
  53337. return PlaySoundAction;
  53338. }(BABYLON.Action));
  53339. BABYLON.PlaySoundAction = PlaySoundAction;
  53340. var StopSoundAction = /** @class */ (function (_super) {
  53341. __extends(StopSoundAction, _super);
  53342. function StopSoundAction(triggerOptions, sound, condition) {
  53343. var _this = _super.call(this, triggerOptions, condition) || this;
  53344. _this._sound = sound;
  53345. return _this;
  53346. }
  53347. StopSoundAction.prototype._prepare = function () {
  53348. };
  53349. StopSoundAction.prototype.execute = function () {
  53350. if (this._sound !== undefined)
  53351. this._sound.stop();
  53352. };
  53353. StopSoundAction.prototype.serialize = function (parent) {
  53354. return _super.prototype._serialize.call(this, {
  53355. name: "StopSoundAction",
  53356. properties: [{ name: "sound", value: this._sound.name }]
  53357. }, parent);
  53358. };
  53359. return StopSoundAction;
  53360. }(BABYLON.Action));
  53361. BABYLON.StopSoundAction = StopSoundAction;
  53362. })(BABYLON || (BABYLON = {}));
  53363. //# sourceMappingURL=babylon.directActions.js.map
  53364. var BABYLON;
  53365. (function (BABYLON) {
  53366. var SpriteManager = /** @class */ (function () {
  53367. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53368. if (epsilon === void 0) { epsilon = 0.01; }
  53369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53370. this.name = name;
  53371. this.sprites = new Array();
  53372. this.renderingGroupId = 0;
  53373. this.layerMask = 0x0FFFFFFF;
  53374. this.fogEnabled = true;
  53375. this.isPickable = false;
  53376. /**
  53377. * An event triggered when the manager is disposed.
  53378. */
  53379. this.onDisposeObservable = new BABYLON.Observable();
  53380. this._vertexBuffers = {};
  53381. this._capacity = capacity;
  53382. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53383. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53384. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53385. if (cellSize.width && cellSize.height) {
  53386. this.cellWidth = cellSize.width;
  53387. this.cellHeight = cellSize.height;
  53388. }
  53389. else if (cellSize !== undefined) {
  53390. this.cellWidth = cellSize;
  53391. this.cellHeight = cellSize;
  53392. }
  53393. else {
  53394. return;
  53395. }
  53396. this._epsilon = epsilon;
  53397. this._scene = scene;
  53398. this._scene.spriteManagers.push(this);
  53399. var indices = [];
  53400. var index = 0;
  53401. for (var count = 0; count < capacity; count++) {
  53402. indices.push(index);
  53403. indices.push(index + 1);
  53404. indices.push(index + 2);
  53405. indices.push(index);
  53406. indices.push(index + 2);
  53407. indices.push(index + 3);
  53408. index += 4;
  53409. }
  53410. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53411. // VBO
  53412. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53413. this._vertexData = new Float32Array(capacity * 16 * 4);
  53414. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53415. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53416. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53417. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53418. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53419. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53420. this._vertexBuffers["options"] = options;
  53421. this._vertexBuffers["cellInfo"] = cellInfo;
  53422. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53423. // Effects
  53424. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53425. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53426. }
  53427. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53428. set: function (callback) {
  53429. if (this._onDisposeObserver) {
  53430. this.onDisposeObservable.remove(this._onDisposeObserver);
  53431. }
  53432. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53433. },
  53434. enumerable: true,
  53435. configurable: true
  53436. });
  53437. Object.defineProperty(SpriteManager.prototype, "texture", {
  53438. get: function () {
  53439. return this._spriteTexture;
  53440. },
  53441. set: function (value) {
  53442. this._spriteTexture = value;
  53443. },
  53444. enumerable: true,
  53445. configurable: true
  53446. });
  53447. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53448. var arrayOffset = index * 16;
  53449. if (offsetX === 0)
  53450. offsetX = this._epsilon;
  53451. else if (offsetX === 1)
  53452. offsetX = 1 - this._epsilon;
  53453. if (offsetY === 0)
  53454. offsetY = this._epsilon;
  53455. else if (offsetY === 1)
  53456. offsetY = 1 - this._epsilon;
  53457. this._vertexData[arrayOffset] = sprite.position.x;
  53458. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53459. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53460. this._vertexData[arrayOffset + 3] = sprite.angle;
  53461. this._vertexData[arrayOffset + 4] = sprite.width;
  53462. this._vertexData[arrayOffset + 5] = sprite.height;
  53463. this._vertexData[arrayOffset + 6] = offsetX;
  53464. this._vertexData[arrayOffset + 7] = offsetY;
  53465. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53466. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53467. var offset = (sprite.cellIndex / rowSize) >> 0;
  53468. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53469. this._vertexData[arrayOffset + 11] = offset;
  53470. // Color
  53471. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53472. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53473. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53474. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53475. };
  53476. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53477. var count = Math.min(this._capacity, this.sprites.length);
  53478. var min = BABYLON.Vector3.Zero();
  53479. var max = BABYLON.Vector3.Zero();
  53480. var distance = Number.MAX_VALUE;
  53481. var currentSprite = null;
  53482. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53483. var cameraView = camera.getViewMatrix();
  53484. for (var index = 0; index < count; index++) {
  53485. var sprite = this.sprites[index];
  53486. if (!sprite) {
  53487. continue;
  53488. }
  53489. if (predicate) {
  53490. if (!predicate(sprite)) {
  53491. continue;
  53492. }
  53493. }
  53494. else if (!sprite.isPickable) {
  53495. continue;
  53496. }
  53497. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53498. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53499. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53500. if (ray.intersectsBoxMinMax(min, max)) {
  53501. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53502. if (distance > currentDistance) {
  53503. distance = currentDistance;
  53504. currentSprite = sprite;
  53505. if (fastCheck) {
  53506. break;
  53507. }
  53508. }
  53509. }
  53510. }
  53511. if (currentSprite) {
  53512. var result = new BABYLON.PickingInfo();
  53513. result.hit = true;
  53514. result.pickedSprite = currentSprite;
  53515. result.distance = distance;
  53516. return result;
  53517. }
  53518. return null;
  53519. };
  53520. SpriteManager.prototype.render = function () {
  53521. // Check
  53522. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53523. return;
  53524. var engine = this._scene.getEngine();
  53525. var baseSize = this._spriteTexture.getBaseSize();
  53526. // Sprites
  53527. var deltaTime = engine.getDeltaTime();
  53528. var max = Math.min(this._capacity, this.sprites.length);
  53529. var rowSize = baseSize.width / this.cellWidth;
  53530. var offset = 0;
  53531. for (var index = 0; index < max; index++) {
  53532. var sprite = this.sprites[index];
  53533. if (!sprite || !sprite.isVisible) {
  53534. continue;
  53535. }
  53536. sprite._animate(deltaTime);
  53537. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53538. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53539. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53540. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53541. }
  53542. this._buffer.update(this._vertexData);
  53543. // Render
  53544. var effect = this._effectBase;
  53545. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53546. effect = this._effectFog;
  53547. }
  53548. engine.enableEffect(effect);
  53549. var viewMatrix = this._scene.getViewMatrix();
  53550. effect.setTexture("diffuseSampler", this._spriteTexture);
  53551. effect.setMatrix("view", viewMatrix);
  53552. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53553. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53554. // Fog
  53555. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53556. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53557. effect.setColor3("vFogColor", this._scene.fogColor);
  53558. }
  53559. // VBOs
  53560. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53561. // Draw order
  53562. engine.setDepthFunctionToLessOrEqual();
  53563. effect.setBool("alphaTest", true);
  53564. engine.setColorWrite(false);
  53565. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53566. engine.setColorWrite(true);
  53567. effect.setBool("alphaTest", false);
  53568. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53569. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53570. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53571. };
  53572. SpriteManager.prototype.dispose = function () {
  53573. if (this._buffer) {
  53574. this._buffer.dispose();
  53575. this._buffer = null;
  53576. }
  53577. if (this._indexBuffer) {
  53578. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53579. this._indexBuffer = null;
  53580. }
  53581. if (this._spriteTexture) {
  53582. this._spriteTexture.dispose();
  53583. this._spriteTexture = null;
  53584. }
  53585. // Remove from scene
  53586. var index = this._scene.spriteManagers.indexOf(this);
  53587. this._scene.spriteManagers.splice(index, 1);
  53588. // Callback
  53589. this.onDisposeObservable.notifyObservers(this);
  53590. this.onDisposeObservable.clear();
  53591. };
  53592. return SpriteManager;
  53593. }());
  53594. BABYLON.SpriteManager = SpriteManager;
  53595. })(BABYLON || (BABYLON = {}));
  53596. //# sourceMappingURL=babylon.spriteManager.js.map
  53597. var BABYLON;
  53598. (function (BABYLON) {
  53599. var Sprite = /** @class */ (function () {
  53600. function Sprite(name, manager) {
  53601. this.name = name;
  53602. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53603. this.width = 1.0;
  53604. this.height = 1.0;
  53605. this.angle = 0;
  53606. this.cellIndex = 0;
  53607. this.invertU = 0;
  53608. this.invertV = 0;
  53609. this.animations = new Array();
  53610. this.isPickable = false;
  53611. this._animationStarted = false;
  53612. this._loopAnimation = false;
  53613. this._fromIndex = 0;
  53614. this._toIndex = 0;
  53615. this._delay = 0;
  53616. this._direction = 1;
  53617. this._time = 0;
  53618. /**
  53619. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53620. */
  53621. this.isVisible = true;
  53622. this._manager = manager;
  53623. this._manager.sprites.push(this);
  53624. this.position = BABYLON.Vector3.Zero();
  53625. }
  53626. Object.defineProperty(Sprite.prototype, "size", {
  53627. get: function () {
  53628. return this.width;
  53629. },
  53630. set: function (value) {
  53631. this.width = value;
  53632. this.height = value;
  53633. },
  53634. enumerable: true,
  53635. configurable: true
  53636. });
  53637. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53638. this._fromIndex = from;
  53639. this._toIndex = to;
  53640. this._loopAnimation = loop;
  53641. this._delay = delay;
  53642. this._animationStarted = true;
  53643. this._direction = from < to ? 1 : -1;
  53644. this.cellIndex = from;
  53645. this._time = 0;
  53646. this._onAnimationEnd = onAnimationEnd;
  53647. };
  53648. Sprite.prototype.stopAnimation = function () {
  53649. this._animationStarted = false;
  53650. };
  53651. Sprite.prototype._animate = function (deltaTime) {
  53652. if (!this._animationStarted)
  53653. return;
  53654. this._time += deltaTime;
  53655. if (this._time > this._delay) {
  53656. this._time = this._time % this._delay;
  53657. this.cellIndex += this._direction;
  53658. if (this.cellIndex > this._toIndex) {
  53659. if (this._loopAnimation) {
  53660. this.cellIndex = this._fromIndex;
  53661. }
  53662. else {
  53663. this.cellIndex = this._toIndex;
  53664. this._animationStarted = false;
  53665. if (this._onAnimationEnd) {
  53666. this._onAnimationEnd();
  53667. }
  53668. if (this.disposeWhenFinishedAnimating) {
  53669. this.dispose();
  53670. }
  53671. }
  53672. }
  53673. }
  53674. };
  53675. Sprite.prototype.dispose = function () {
  53676. for (var i = 0; i < this._manager.sprites.length; i++) {
  53677. if (this._manager.sprites[i] == this) {
  53678. this._manager.sprites.splice(i, 1);
  53679. }
  53680. }
  53681. };
  53682. return Sprite;
  53683. }());
  53684. BABYLON.Sprite = Sprite;
  53685. })(BABYLON || (BABYLON = {}));
  53686. //# sourceMappingURL=babylon.sprite.js.map
  53687. var BABYLON;
  53688. (function (BABYLON) {
  53689. var IntersectionInfo = /** @class */ (function () {
  53690. function IntersectionInfo(bu, bv, distance) {
  53691. this.bu = bu;
  53692. this.bv = bv;
  53693. this.distance = distance;
  53694. this.faceId = 0;
  53695. this.subMeshId = 0;
  53696. }
  53697. return IntersectionInfo;
  53698. }());
  53699. BABYLON.IntersectionInfo = IntersectionInfo;
  53700. /**
  53701. * Information about the result of picking within a scene
  53702. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53703. */
  53704. var PickingInfo = /** @class */ (function () {
  53705. function PickingInfo() {
  53706. /**
  53707. * If the pick collided with an object
  53708. */
  53709. this.hit = false;
  53710. /**
  53711. * Distance away where the pick collided
  53712. */
  53713. this.distance = 0;
  53714. /**
  53715. * The location of pick collision
  53716. */
  53717. this.pickedPoint = null;
  53718. /**
  53719. * The mesh corrisponding the the pick collision
  53720. */
  53721. this.pickedMesh = null;
  53722. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53723. this.bu = 0;
  53724. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53725. this.bv = 0;
  53726. /** The id of the face on the mesh that was picked */
  53727. this.faceId = -1;
  53728. /** Id of the the submesh that was picked */
  53729. this.subMeshId = 0;
  53730. /** If a sprite was picked, this will be the sprite the pick collided with */
  53731. this.pickedSprite = null;
  53732. /**
  53733. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53734. */
  53735. this.originMesh = null;
  53736. /**
  53737. * The ray that was used to perform the picking.
  53738. */
  53739. this.ray = null;
  53740. }
  53741. /**
  53742. * Gets the normal corrispodning to the face the pick collided with
  53743. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53744. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53745. * @returns The normal corrispodning to the face the pick collided with
  53746. */
  53747. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53748. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53749. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53750. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53751. return null;
  53752. }
  53753. var indices = this.pickedMesh.getIndices();
  53754. if (!indices) {
  53755. return null;
  53756. }
  53757. var result;
  53758. if (useVerticesNormals) {
  53759. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53760. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53761. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53762. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53763. normal0 = normal0.scale(this.bu);
  53764. normal1 = normal1.scale(this.bv);
  53765. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53766. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53767. }
  53768. else {
  53769. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53770. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53771. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53772. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53773. var p1p2 = vertex1.subtract(vertex2);
  53774. var p3p2 = vertex3.subtract(vertex2);
  53775. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53776. }
  53777. if (useWorldCoordinates) {
  53778. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  53779. }
  53780. return BABYLON.Vector3.Normalize(result);
  53781. };
  53782. /**
  53783. * Gets the texture coordinates of where the pick occured
  53784. * @returns the vector containing the coordnates of the texture
  53785. */
  53786. PickingInfo.prototype.getTextureCoordinates = function () {
  53787. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53788. return null;
  53789. }
  53790. var indices = this.pickedMesh.getIndices();
  53791. if (!indices) {
  53792. return null;
  53793. }
  53794. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53795. if (!uvs) {
  53796. return null;
  53797. }
  53798. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53799. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53800. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53801. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53802. uv1 = uv1.scale(this.bu);
  53803. uv2 = uv2.scale(this.bv);
  53804. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53805. };
  53806. return PickingInfo;
  53807. }());
  53808. BABYLON.PickingInfo = PickingInfo;
  53809. })(BABYLON || (BABYLON = {}));
  53810. //# sourceMappingURL=babylon.pickingInfo.js.map
  53811. var BABYLON;
  53812. (function (BABYLON) {
  53813. var Ray = /** @class */ (function () {
  53814. function Ray(origin, direction, length) {
  53815. if (length === void 0) { length = Number.MAX_VALUE; }
  53816. this.origin = origin;
  53817. this.direction = direction;
  53818. this.length = length;
  53819. }
  53820. // Methods
  53821. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53822. var d = 0.0;
  53823. var maxValue = Number.MAX_VALUE;
  53824. var inv;
  53825. var min;
  53826. var max;
  53827. var temp;
  53828. if (Math.abs(this.direction.x) < 0.0000001) {
  53829. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53830. return false;
  53831. }
  53832. }
  53833. else {
  53834. inv = 1.0 / this.direction.x;
  53835. min = (minimum.x - this.origin.x) * inv;
  53836. max = (maximum.x - this.origin.x) * inv;
  53837. if (max === -Infinity) {
  53838. max = Infinity;
  53839. }
  53840. if (min > max) {
  53841. temp = min;
  53842. min = max;
  53843. max = temp;
  53844. }
  53845. d = Math.max(min, d);
  53846. maxValue = Math.min(max, maxValue);
  53847. if (d > maxValue) {
  53848. return false;
  53849. }
  53850. }
  53851. if (Math.abs(this.direction.y) < 0.0000001) {
  53852. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53853. return false;
  53854. }
  53855. }
  53856. else {
  53857. inv = 1.0 / this.direction.y;
  53858. min = (minimum.y - this.origin.y) * inv;
  53859. max = (maximum.y - this.origin.y) * inv;
  53860. if (max === -Infinity) {
  53861. max = Infinity;
  53862. }
  53863. if (min > max) {
  53864. temp = min;
  53865. min = max;
  53866. max = temp;
  53867. }
  53868. d = Math.max(min, d);
  53869. maxValue = Math.min(max, maxValue);
  53870. if (d > maxValue) {
  53871. return false;
  53872. }
  53873. }
  53874. if (Math.abs(this.direction.z) < 0.0000001) {
  53875. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53876. return false;
  53877. }
  53878. }
  53879. else {
  53880. inv = 1.0 / this.direction.z;
  53881. min = (minimum.z - this.origin.z) * inv;
  53882. max = (maximum.z - this.origin.z) * inv;
  53883. if (max === -Infinity) {
  53884. max = Infinity;
  53885. }
  53886. if (min > max) {
  53887. temp = min;
  53888. min = max;
  53889. max = temp;
  53890. }
  53891. d = Math.max(min, d);
  53892. maxValue = Math.min(max, maxValue);
  53893. if (d > maxValue) {
  53894. return false;
  53895. }
  53896. }
  53897. return true;
  53898. };
  53899. Ray.prototype.intersectsBox = function (box) {
  53900. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53901. };
  53902. Ray.prototype.intersectsSphere = function (sphere) {
  53903. var x = sphere.center.x - this.origin.x;
  53904. var y = sphere.center.y - this.origin.y;
  53905. var z = sphere.center.z - this.origin.z;
  53906. var pyth = (x * x) + (y * y) + (z * z);
  53907. var rr = sphere.radius * sphere.radius;
  53908. if (pyth <= rr) {
  53909. return true;
  53910. }
  53911. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  53912. if (dot < 0.0) {
  53913. return false;
  53914. }
  53915. var temp = pyth - (dot * dot);
  53916. return temp <= rr;
  53917. };
  53918. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  53919. if (!this._edge1) {
  53920. this._edge1 = BABYLON.Vector3.Zero();
  53921. this._edge2 = BABYLON.Vector3.Zero();
  53922. this._pvec = BABYLON.Vector3.Zero();
  53923. this._tvec = BABYLON.Vector3.Zero();
  53924. this._qvec = BABYLON.Vector3.Zero();
  53925. }
  53926. vertex1.subtractToRef(vertex0, this._edge1);
  53927. vertex2.subtractToRef(vertex0, this._edge2);
  53928. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  53929. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  53930. if (det === 0) {
  53931. return null;
  53932. }
  53933. var invdet = 1 / det;
  53934. this.origin.subtractToRef(vertex0, this._tvec);
  53935. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  53936. if (bu < 0 || bu > 1.0) {
  53937. return null;
  53938. }
  53939. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  53940. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  53941. if (bv < 0 || bu + bv > 1.0) {
  53942. return null;
  53943. }
  53944. //check if the distance is longer than the predefined length.
  53945. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  53946. if (distance > this.length) {
  53947. return null;
  53948. }
  53949. return new BABYLON.IntersectionInfo(bu, bv, distance);
  53950. };
  53951. Ray.prototype.intersectsPlane = function (plane) {
  53952. var distance;
  53953. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  53954. if (Math.abs(result1) < 9.99999997475243E-07) {
  53955. return null;
  53956. }
  53957. else {
  53958. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  53959. distance = (-plane.d - result2) / result1;
  53960. if (distance < 0.0) {
  53961. if (distance < -9.99999997475243E-07) {
  53962. return null;
  53963. }
  53964. else {
  53965. return 0;
  53966. }
  53967. }
  53968. return distance;
  53969. }
  53970. };
  53971. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  53972. var tm = BABYLON.Tmp.Matrix[0];
  53973. mesh.getWorldMatrix().invertToRef(tm);
  53974. if (this._tmpRay) {
  53975. Ray.TransformToRef(this, tm, this._tmpRay);
  53976. }
  53977. else {
  53978. this._tmpRay = Ray.Transform(this, tm);
  53979. }
  53980. return mesh.intersects(this._tmpRay, fastCheck);
  53981. };
  53982. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  53983. if (results) {
  53984. results.length = 0;
  53985. }
  53986. else {
  53987. results = [];
  53988. }
  53989. for (var i = 0; i < meshes.length; i++) {
  53990. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  53991. if (pickInfo.hit) {
  53992. results.push(pickInfo);
  53993. }
  53994. }
  53995. results.sort(this._comparePickingInfo);
  53996. return results;
  53997. };
  53998. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  53999. if (pickingInfoA.distance < pickingInfoB.distance) {
  54000. return -1;
  54001. }
  54002. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54003. return 1;
  54004. }
  54005. else {
  54006. return 0;
  54007. }
  54008. };
  54009. /**
  54010. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54011. * @param sega the first point of the segment to test the intersection against
  54012. * @param segb the second point of the segment to test the intersection against
  54013. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54014. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54015. */
  54016. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54017. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54018. var u = segb.subtract(sega);
  54019. var v = rsegb.subtract(this.origin);
  54020. var w = sega.subtract(this.origin);
  54021. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54022. var b = BABYLON.Vector3.Dot(u, v);
  54023. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54024. var d = BABYLON.Vector3.Dot(u, w);
  54025. var e = BABYLON.Vector3.Dot(v, w);
  54026. var D = a * c - b * b; // always >= 0
  54027. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54028. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54029. // compute the line parameters of the two closest points
  54030. if (D < Ray.smallnum) { // the lines are almost parallel
  54031. sN = 0.0; // force using point P0 on segment S1
  54032. sD = 1.0; // to prevent possible division by 0.0 later
  54033. tN = e;
  54034. tD = c;
  54035. }
  54036. else { // get the closest points on the infinite lines
  54037. sN = (b * e - c * d);
  54038. tN = (a * e - b * d);
  54039. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54040. sN = 0.0;
  54041. tN = e;
  54042. tD = c;
  54043. }
  54044. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54045. sN = sD;
  54046. tN = e + b;
  54047. tD = c;
  54048. }
  54049. }
  54050. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54051. tN = 0.0;
  54052. // recompute sc for this edge
  54053. if (-d < 0.0) {
  54054. sN = 0.0;
  54055. }
  54056. else if (-d > a)
  54057. sN = sD;
  54058. else {
  54059. sN = -d;
  54060. sD = a;
  54061. }
  54062. }
  54063. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54064. tN = tD;
  54065. // recompute sc for this edge
  54066. if ((-d + b) < 0.0) {
  54067. sN = 0;
  54068. }
  54069. else if ((-d + b) > a) {
  54070. sN = sD;
  54071. }
  54072. else {
  54073. sN = (-d + b);
  54074. sD = a;
  54075. }
  54076. }
  54077. // finally do the division to get sc and tc
  54078. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54079. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54080. // get the difference of the two closest points
  54081. var qtc = v.multiplyByFloats(tc, tc, tc);
  54082. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54083. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54084. if (isIntersected) {
  54085. return qtc.length();
  54086. }
  54087. return -1;
  54088. };
  54089. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54090. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54091. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54092. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54093. this.direction.normalize();
  54094. return this;
  54095. };
  54096. // Statics
  54097. Ray.Zero = function () {
  54098. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54099. };
  54100. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54101. var result = Ray.Zero();
  54102. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54103. };
  54104. /**
  54105. * 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
  54106. * transformed to the given world matrix.
  54107. * @param origin The origin point
  54108. * @param end The end point
  54109. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54110. */
  54111. Ray.CreateNewFromTo = function (origin, end, world) {
  54112. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54113. var direction = end.subtract(origin);
  54114. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54115. direction.normalize();
  54116. return Ray.Transform(new Ray(origin, direction, length), world);
  54117. };
  54118. Ray.Transform = function (ray, matrix) {
  54119. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54120. Ray.TransformToRef(ray, matrix, result);
  54121. return result;
  54122. };
  54123. Ray.TransformToRef = function (ray, matrix, result) {
  54124. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54125. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54126. result.length = ray.length;
  54127. var dir = result.direction;
  54128. var len = dir.length();
  54129. if (!(len === 0 || len === 1)) {
  54130. var num = 1.0 / len;
  54131. dir.x *= num;
  54132. dir.y *= num;
  54133. dir.z *= num;
  54134. result.length *= len;
  54135. }
  54136. };
  54137. Ray.smallnum = 0.00000001;
  54138. Ray.rayl = 10e8;
  54139. return Ray;
  54140. }());
  54141. BABYLON.Ray = Ray;
  54142. })(BABYLON || (BABYLON = {}));
  54143. //# sourceMappingURL=babylon.ray.js.map
  54144. var BABYLON;
  54145. (function (BABYLON) {
  54146. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54147. if (boxMin.x > sphereCenter.x + sphereRadius)
  54148. return false;
  54149. if (sphereCenter.x - sphereRadius > boxMax.x)
  54150. return false;
  54151. if (boxMin.y > sphereCenter.y + sphereRadius)
  54152. return false;
  54153. if (sphereCenter.y - sphereRadius > boxMax.y)
  54154. return false;
  54155. if (boxMin.z > sphereCenter.z + sphereRadius)
  54156. return false;
  54157. if (sphereCenter.z - sphereRadius > boxMax.z)
  54158. return false;
  54159. return true;
  54160. };
  54161. var getLowestRoot = (function () {
  54162. var result = { root: 0, found: false };
  54163. return function (a, b, c, maxR) {
  54164. result.root = 0;
  54165. result.found = false;
  54166. var determinant = b * b - 4.0 * a * c;
  54167. if (determinant < 0)
  54168. return result;
  54169. var sqrtD = Math.sqrt(determinant);
  54170. var r1 = (-b - sqrtD) / (2.0 * a);
  54171. var r2 = (-b + sqrtD) / (2.0 * a);
  54172. if (r1 > r2) {
  54173. var temp = r2;
  54174. r2 = r1;
  54175. r1 = temp;
  54176. }
  54177. if (r1 > 0 && r1 < maxR) {
  54178. result.root = r1;
  54179. result.found = true;
  54180. return result;
  54181. }
  54182. if (r2 > 0 && r2 < maxR) {
  54183. result.root = r2;
  54184. result.found = true;
  54185. return result;
  54186. }
  54187. return result;
  54188. };
  54189. })();
  54190. var Collider = /** @class */ (function () {
  54191. function Collider() {
  54192. this._collisionPoint = BABYLON.Vector3.Zero();
  54193. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54194. this._tempVector = BABYLON.Vector3.Zero();
  54195. this._tempVector2 = BABYLON.Vector3.Zero();
  54196. this._tempVector3 = BABYLON.Vector3.Zero();
  54197. this._tempVector4 = BABYLON.Vector3.Zero();
  54198. this._edge = BABYLON.Vector3.Zero();
  54199. this._baseToVertex = BABYLON.Vector3.Zero();
  54200. this._destinationPoint = BABYLON.Vector3.Zero();
  54201. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54202. this._displacementVector = BABYLON.Vector3.Zero();
  54203. this._radius = BABYLON.Vector3.One();
  54204. this._retry = 0;
  54205. this._basePointWorld = BABYLON.Vector3.Zero();
  54206. this._velocityWorld = BABYLON.Vector3.Zero();
  54207. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54208. this._collisionMask = -1;
  54209. }
  54210. Object.defineProperty(Collider.prototype, "collisionMask", {
  54211. get: function () {
  54212. return this._collisionMask;
  54213. },
  54214. set: function (mask) {
  54215. this._collisionMask = !isNaN(mask) ? mask : -1;
  54216. },
  54217. enumerable: true,
  54218. configurable: true
  54219. });
  54220. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54221. /**
  54222. * Gets the plane normal used to compute the sliding response (in local space)
  54223. */
  54224. get: function () {
  54225. return this._slidePlaneNormal;
  54226. },
  54227. enumerable: true,
  54228. configurable: true
  54229. });
  54230. // Methods
  54231. Collider.prototype._initialize = function (source, dir, e) {
  54232. this._velocity = dir;
  54233. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54234. this._basePoint = source;
  54235. source.multiplyToRef(this._radius, this._basePointWorld);
  54236. dir.multiplyToRef(this._radius, this._velocityWorld);
  54237. this._velocityWorldLength = this._velocityWorld.length();
  54238. this._epsilon = e;
  54239. this.collisionFound = false;
  54240. };
  54241. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54242. pa.subtractToRef(point, this._tempVector);
  54243. pb.subtractToRef(point, this._tempVector2);
  54244. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54245. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54246. if (d < 0)
  54247. return false;
  54248. pc.subtractToRef(point, this._tempVector3);
  54249. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54250. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54251. if (d < 0)
  54252. return false;
  54253. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54254. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54255. return d >= 0;
  54256. };
  54257. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54258. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54259. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54260. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54261. return false;
  54262. }
  54263. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54264. return false;
  54265. return true;
  54266. };
  54267. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54268. var t0;
  54269. var embeddedInPlane = false;
  54270. //defensive programming, actually not needed.
  54271. if (!trianglePlaneArray) {
  54272. trianglePlaneArray = [];
  54273. }
  54274. if (!trianglePlaneArray[faceIndex]) {
  54275. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54276. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54277. }
  54278. var trianglePlane = trianglePlaneArray[faceIndex];
  54279. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54280. return;
  54281. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54282. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54283. if (normalDotVelocity == 0) {
  54284. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54285. return;
  54286. embeddedInPlane = true;
  54287. t0 = 0;
  54288. }
  54289. else {
  54290. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54291. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54292. if (t0 > t1) {
  54293. var temp = t1;
  54294. t1 = t0;
  54295. t0 = temp;
  54296. }
  54297. if (t0 > 1.0 || t1 < 0.0)
  54298. return;
  54299. if (t0 < 0)
  54300. t0 = 0;
  54301. if (t0 > 1.0)
  54302. t0 = 1.0;
  54303. }
  54304. this._collisionPoint.copyFromFloats(0, 0, 0);
  54305. var found = false;
  54306. var t = 1.0;
  54307. if (!embeddedInPlane) {
  54308. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54309. this._velocity.scaleToRef(t0, this._tempVector);
  54310. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54311. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54312. found = true;
  54313. t = t0;
  54314. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54315. }
  54316. }
  54317. if (!found) {
  54318. var velocitySquaredLength = this._velocity.lengthSquared();
  54319. var a = velocitySquaredLength;
  54320. this._basePoint.subtractToRef(p1, this._tempVector);
  54321. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54322. var c = this._tempVector.lengthSquared() - 1.0;
  54323. var lowestRoot = getLowestRoot(a, b, c, t);
  54324. if (lowestRoot.found) {
  54325. t = lowestRoot.root;
  54326. found = true;
  54327. this._collisionPoint.copyFrom(p1);
  54328. }
  54329. this._basePoint.subtractToRef(p2, this._tempVector);
  54330. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54331. c = this._tempVector.lengthSquared() - 1.0;
  54332. lowestRoot = getLowestRoot(a, b, c, t);
  54333. if (lowestRoot.found) {
  54334. t = lowestRoot.root;
  54335. found = true;
  54336. this._collisionPoint.copyFrom(p2);
  54337. }
  54338. this._basePoint.subtractToRef(p3, this._tempVector);
  54339. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54340. c = this._tempVector.lengthSquared() - 1.0;
  54341. lowestRoot = getLowestRoot(a, b, c, t);
  54342. if (lowestRoot.found) {
  54343. t = lowestRoot.root;
  54344. found = true;
  54345. this._collisionPoint.copyFrom(p3);
  54346. }
  54347. p2.subtractToRef(p1, this._edge);
  54348. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54349. var edgeSquaredLength = this._edge.lengthSquared();
  54350. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54351. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54352. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54353. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54354. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54355. lowestRoot = getLowestRoot(a, b, c, t);
  54356. if (lowestRoot.found) {
  54357. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54358. if (f >= 0.0 && f <= 1.0) {
  54359. t = lowestRoot.root;
  54360. found = true;
  54361. this._edge.scaleInPlace(f);
  54362. p1.addToRef(this._edge, this._collisionPoint);
  54363. }
  54364. }
  54365. p3.subtractToRef(p2, this._edge);
  54366. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54367. edgeSquaredLength = this._edge.lengthSquared();
  54368. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54369. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54370. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54371. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54372. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54373. lowestRoot = getLowestRoot(a, b, c, t);
  54374. if (lowestRoot.found) {
  54375. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54376. if (f >= 0.0 && f <= 1.0) {
  54377. t = lowestRoot.root;
  54378. found = true;
  54379. this._edge.scaleInPlace(f);
  54380. p2.addToRef(this._edge, this._collisionPoint);
  54381. }
  54382. }
  54383. p1.subtractToRef(p3, this._edge);
  54384. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54385. edgeSquaredLength = this._edge.lengthSquared();
  54386. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54387. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54388. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54389. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54390. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54391. lowestRoot = getLowestRoot(a, b, c, t);
  54392. if (lowestRoot.found) {
  54393. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54394. if (f >= 0.0 && f <= 1.0) {
  54395. t = lowestRoot.root;
  54396. found = true;
  54397. this._edge.scaleInPlace(f);
  54398. p3.addToRef(this._edge, this._collisionPoint);
  54399. }
  54400. }
  54401. }
  54402. if (found) {
  54403. var distToCollision = t * this._velocity.length();
  54404. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54405. if (!this.intersectionPoint) {
  54406. this.intersectionPoint = this._collisionPoint.clone();
  54407. }
  54408. else {
  54409. this.intersectionPoint.copyFrom(this._collisionPoint);
  54410. }
  54411. this._nearestDistance = distToCollision;
  54412. this.collisionFound = true;
  54413. }
  54414. }
  54415. };
  54416. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54417. for (var i = indexStart; i < indexEnd; i += 3) {
  54418. var p1 = pts[indices[i] - decal];
  54419. var p2 = pts[indices[i + 1] - decal];
  54420. var p3 = pts[indices[i + 2] - decal];
  54421. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54422. }
  54423. };
  54424. Collider.prototype._getResponse = function (pos, vel) {
  54425. pos.addToRef(vel, this._destinationPoint);
  54426. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54427. this._basePoint.addToRef(vel, pos);
  54428. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54429. this._slidePlaneNormal.normalize();
  54430. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54431. pos.addInPlace(this._displacementVector);
  54432. this.intersectionPoint.addInPlace(this._displacementVector);
  54433. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54434. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54435. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54436. };
  54437. return Collider;
  54438. }());
  54439. BABYLON.Collider = Collider;
  54440. })(BABYLON || (BABYLON = {}));
  54441. //# sourceMappingURL=babylon.collider.js.map
  54442. var BABYLON;
  54443. (function (BABYLON) {
  54444. //WebWorker code will be inserted to this variable.
  54445. BABYLON.CollisionWorker = "";
  54446. /** Defines supported task for worker process */
  54447. var WorkerTaskType;
  54448. (function (WorkerTaskType) {
  54449. /** Initialization */
  54450. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54451. /** Update of geometry */
  54452. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54453. /** Evaluate collision */
  54454. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54455. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54456. /** Defines kind of replies returned by worker */
  54457. var WorkerReplyType;
  54458. (function (WorkerReplyType) {
  54459. /** Success */
  54460. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54461. /** Unkown error */
  54462. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54463. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54464. var CollisionCoordinatorWorker = /** @class */ (function () {
  54465. function CollisionCoordinatorWorker() {
  54466. var _this = this;
  54467. this._scaledPosition = BABYLON.Vector3.Zero();
  54468. this._scaledVelocity = BABYLON.Vector3.Zero();
  54469. this.onMeshUpdated = function (transformNode) {
  54470. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54471. };
  54472. this.onGeometryUpdated = function (geometry) {
  54473. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54474. };
  54475. this._afterRender = function () {
  54476. if (!_this._init)
  54477. return;
  54478. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54479. return;
  54480. }
  54481. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54482. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54483. if (_this._runningUpdated > 4) {
  54484. return;
  54485. }
  54486. ++_this._runningUpdated;
  54487. var payload = {
  54488. updatedMeshes: _this._addUpdateMeshesList,
  54489. updatedGeometries: _this._addUpdateGeometriesList,
  54490. removedGeometries: _this._toRemoveGeometryArray,
  54491. removedMeshes: _this._toRemoveMeshesArray
  54492. };
  54493. var message = {
  54494. payload: payload,
  54495. taskType: WorkerTaskType.UPDATE
  54496. };
  54497. var serializable = [];
  54498. for (var id in payload.updatedGeometries) {
  54499. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54500. //prepare transferables
  54501. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54502. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54503. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54504. }
  54505. }
  54506. _this._worker.postMessage(message, serializable);
  54507. _this._addUpdateMeshesList = {};
  54508. _this._addUpdateGeometriesList = {};
  54509. _this._toRemoveGeometryArray = [];
  54510. _this._toRemoveMeshesArray = [];
  54511. };
  54512. this._onMessageFromWorker = function (e) {
  54513. var returnData = e.data;
  54514. if (returnData.error != WorkerReplyType.SUCCESS) {
  54515. //TODO what errors can be returned from the worker?
  54516. BABYLON.Tools.Warn("error returned from worker!");
  54517. return;
  54518. }
  54519. switch (returnData.taskType) {
  54520. case WorkerTaskType.INIT:
  54521. _this._init = true;
  54522. //Update the worked with ALL of the scene's current state
  54523. _this._scene.meshes.forEach(function (mesh) {
  54524. _this.onMeshAdded(mesh);
  54525. });
  54526. _this._scene.getGeometries().forEach(function (geometry) {
  54527. _this.onGeometryAdded(geometry);
  54528. });
  54529. break;
  54530. case WorkerTaskType.UPDATE:
  54531. _this._runningUpdated--;
  54532. break;
  54533. case WorkerTaskType.COLLIDE:
  54534. var returnPayload = returnData.payload;
  54535. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54536. return;
  54537. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54538. if (callback) {
  54539. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54540. if (mesh) {
  54541. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54542. }
  54543. }
  54544. //cleanup
  54545. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54546. break;
  54547. }
  54548. };
  54549. this._collisionsCallbackArray = [];
  54550. this._init = false;
  54551. this._runningUpdated = 0;
  54552. this._addUpdateMeshesList = {};
  54553. this._addUpdateGeometriesList = {};
  54554. this._toRemoveGeometryArray = [];
  54555. this._toRemoveMeshesArray = [];
  54556. }
  54557. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54558. if (!this._init)
  54559. return;
  54560. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54561. return;
  54562. position.divideToRef(collider._radius, this._scaledPosition);
  54563. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54564. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54565. var payload = {
  54566. collider: {
  54567. position: this._scaledPosition.asArray(),
  54568. velocity: this._scaledVelocity.asArray(),
  54569. radius: collider._radius.asArray()
  54570. },
  54571. collisionId: collisionIndex,
  54572. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54573. maximumRetry: maximumRetry
  54574. };
  54575. var message = {
  54576. payload: payload,
  54577. taskType: WorkerTaskType.COLLIDE
  54578. };
  54579. this._worker.postMessage(message);
  54580. };
  54581. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54582. this._scene = scene;
  54583. this._scene.registerAfterRender(this._afterRender);
  54584. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54585. this._worker = new Worker(workerUrl);
  54586. this._worker.onmessage = this._onMessageFromWorker;
  54587. var message = {
  54588. payload: {},
  54589. taskType: WorkerTaskType.INIT
  54590. };
  54591. this._worker.postMessage(message);
  54592. };
  54593. CollisionCoordinatorWorker.prototype.destroy = function () {
  54594. this._scene.unregisterAfterRender(this._afterRender);
  54595. this._worker.terminate();
  54596. };
  54597. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54598. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54599. this.onMeshUpdated(mesh);
  54600. };
  54601. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54602. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54603. };
  54604. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54605. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54606. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54607. this.onGeometryUpdated(geometry);
  54608. };
  54609. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54610. this._toRemoveGeometryArray.push(geometry.id);
  54611. };
  54612. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54613. var submeshes = [];
  54614. if (mesh.subMeshes) {
  54615. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54616. var boundingInfo = sm.getBoundingInfo();
  54617. return {
  54618. position: idx,
  54619. verticesStart: sm.verticesStart,
  54620. verticesCount: sm.verticesCount,
  54621. indexStart: sm.indexStart,
  54622. indexCount: sm.indexCount,
  54623. hasMaterial: !!sm.getMaterial(),
  54624. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54625. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54626. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54627. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54628. };
  54629. });
  54630. }
  54631. var geometryId = null;
  54632. if (mesh instanceof BABYLON.Mesh) {
  54633. var geometry = mesh.geometry;
  54634. geometryId = geometry ? geometry.id : null;
  54635. }
  54636. else if (mesh instanceof BABYLON.InstancedMesh) {
  54637. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54638. geometryId = geometry ? geometry.id : null;
  54639. }
  54640. var boundingInfo = mesh.getBoundingInfo();
  54641. return {
  54642. uniqueId: mesh.uniqueId,
  54643. id: mesh.id,
  54644. name: mesh.name,
  54645. geometryId: geometryId,
  54646. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54647. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54648. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54649. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54650. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54651. subMeshes: submeshes,
  54652. checkCollisions: mesh.checkCollisions
  54653. };
  54654. };
  54655. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54656. return {
  54657. id: geometry.id,
  54658. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54659. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54660. indices: new Uint32Array(geometry.getIndices() || []),
  54661. };
  54662. };
  54663. return CollisionCoordinatorWorker;
  54664. }());
  54665. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54666. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54667. function CollisionCoordinatorLegacy() {
  54668. this._scaledPosition = BABYLON.Vector3.Zero();
  54669. this._scaledVelocity = BABYLON.Vector3.Zero();
  54670. this._finalPosition = BABYLON.Vector3.Zero();
  54671. }
  54672. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54673. position.divideToRef(collider._radius, this._scaledPosition);
  54674. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54675. collider.collidedMesh = null;
  54676. collider._retry = 0;
  54677. collider._initialVelocity = this._scaledVelocity;
  54678. collider._initialPosition = this._scaledPosition;
  54679. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54680. this._finalPosition.multiplyInPlace(collider._radius);
  54681. //run the callback
  54682. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54683. };
  54684. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54685. this._scene = scene;
  54686. };
  54687. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54688. //Legacy need no destruction method.
  54689. };
  54690. //No update in legacy mode
  54691. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54692. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54693. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54694. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54695. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54696. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54697. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54698. if (excludedMesh === void 0) { excludedMesh = null; }
  54699. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54700. if (collider._retry >= maximumRetry) {
  54701. finalPosition.copyFrom(position);
  54702. return;
  54703. }
  54704. // Check if this is a mesh else camera or -1
  54705. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54706. collider._initialize(position, velocity, closeDistance);
  54707. // Check all meshes
  54708. for (var index = 0; index < this._scene.meshes.length; index++) {
  54709. var mesh = this._scene.meshes[index];
  54710. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54711. mesh._checkCollision(collider);
  54712. }
  54713. }
  54714. if (!collider.collisionFound) {
  54715. position.addToRef(velocity, finalPosition);
  54716. return;
  54717. }
  54718. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54719. collider._getResponse(position, velocity);
  54720. }
  54721. if (velocity.length() <= closeDistance) {
  54722. finalPosition.copyFrom(position);
  54723. return;
  54724. }
  54725. collider._retry++;
  54726. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54727. };
  54728. return CollisionCoordinatorLegacy;
  54729. }());
  54730. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54731. })(BABYLON || (BABYLON = {}));
  54732. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54733. var BABYLON;
  54734. (function (BABYLON) {
  54735. /**
  54736. * A particle represents one of the element emitted by a particle system.
  54737. * This is mainly define by its coordinates, direction, velocity and age.
  54738. */
  54739. var Particle = /** @class */ (function () {
  54740. /**
  54741. * Creates a new instance Particle
  54742. * @param particleSystem the particle system the particle belongs to
  54743. */
  54744. function Particle(
  54745. /**
  54746. * particleSystem the particle system the particle belongs to.
  54747. */
  54748. particleSystem) {
  54749. this.particleSystem = particleSystem;
  54750. /**
  54751. * The world position of the particle in the scene.
  54752. */
  54753. this.position = BABYLON.Vector3.Zero();
  54754. /**
  54755. * The world direction of the particle in the scene.
  54756. */
  54757. this.direction = BABYLON.Vector3.Zero();
  54758. /**
  54759. * The color of the particle.
  54760. */
  54761. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54762. /**
  54763. * The color change of the particle per step.
  54764. */
  54765. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54766. /**
  54767. * Defines how long will the life of the particle be.
  54768. */
  54769. this.lifeTime = 1.0;
  54770. /**
  54771. * The current age of the particle.
  54772. */
  54773. this.age = 0;
  54774. /**
  54775. * The current size of the particle.
  54776. */
  54777. this.size = 0;
  54778. /**
  54779. * The current scale of the particle.
  54780. */
  54781. this.scale = new BABYLON.Vector2(1, 1);
  54782. /**
  54783. * The current angle of the particle.
  54784. */
  54785. this.angle = 0;
  54786. /**
  54787. * Defines how fast is the angle changing.
  54788. */
  54789. this.angularSpeed = 0;
  54790. /**
  54791. * Defines the cell index used by the particle to be rendered from a sprite.
  54792. */
  54793. this.cellIndex = 0;
  54794. this._currentFrameCounter = 0;
  54795. if (!this.particleSystem.isAnimationSheetEnabled) {
  54796. return;
  54797. }
  54798. this.updateCellInfoFromSystem();
  54799. }
  54800. Particle.prototype.updateCellInfoFromSystem = function () {
  54801. this.cellIndex = this.particleSystem.startSpriteCellID;
  54802. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  54803. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  54804. }
  54805. else {
  54806. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  54807. }
  54808. };
  54809. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  54810. // (ageOffset / scaledUpdateSpeed) / available cells
  54811. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  54812. this._currentFrameCounter += scaledUpdateSpeed;
  54813. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  54814. this._currentFrameCounter = 0;
  54815. this.cellIndex++;
  54816. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54817. this.cellIndex = this.particleSystem.endSpriteCellID;
  54818. }
  54819. }
  54820. };
  54821. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  54822. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  54823. this.cellIndex++;
  54824. this._currentFrameCounter = 0;
  54825. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  54826. if (this.particleSystem.spriteCellLoop) {
  54827. this.cellIndex = this.particleSystem.startSpriteCellID;
  54828. }
  54829. else {
  54830. this.cellIndex = this.particleSystem.endSpriteCellID;
  54831. }
  54832. }
  54833. }
  54834. else {
  54835. this._currentFrameCounter++;
  54836. }
  54837. };
  54838. /**
  54839. * Copy the properties of particle to another one.
  54840. * @param other the particle to copy the information to.
  54841. */
  54842. Particle.prototype.copyTo = function (other) {
  54843. other.position.copyFrom(this.position);
  54844. if (this._initialDirection) {
  54845. if (other._initialDirection) {
  54846. other._initialDirection.copyFrom(this._initialDirection);
  54847. }
  54848. else {
  54849. other._initialDirection = this._initialDirection.clone();
  54850. }
  54851. }
  54852. else {
  54853. other._initialDirection = null;
  54854. }
  54855. other.direction.copyFrom(this.direction);
  54856. other.color.copyFrom(this.color);
  54857. other.colorStep.copyFrom(this.colorStep);
  54858. other.lifeTime = this.lifeTime;
  54859. other.age = this.age;
  54860. other.size = this.size;
  54861. other.scale.copyFrom(this.scale);
  54862. other.angle = this.angle;
  54863. other.angularSpeed = this.angularSpeed;
  54864. other.particleSystem = this.particleSystem;
  54865. other.cellIndex = this.cellIndex;
  54866. };
  54867. return Particle;
  54868. }());
  54869. BABYLON.Particle = Particle;
  54870. })(BABYLON || (BABYLON = {}));
  54871. //# sourceMappingURL=babylon.particle.js.map
  54872. var BABYLON;
  54873. (function (BABYLON) {
  54874. /**
  54875. * This represents a particle system in Babylon.
  54876. * 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.
  54877. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54878. * @example https://doc.babylonjs.com/babylon101/particles
  54879. */
  54880. var ParticleSystem = /** @class */ (function () {
  54881. /**
  54882. * Instantiates a particle system.
  54883. * 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.
  54884. * @param name The name of the particle system
  54885. * @param capacity The max number of particles alive at the same time
  54886. * @param scene The scene the particle system belongs to
  54887. * @param customEffect a custom effect used to change the way particles are rendered by default
  54888. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54889. * @param epsilon Offset used to render the particles
  54890. */
  54891. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54892. if (customEffect === void 0) { customEffect = null; }
  54893. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54894. if (epsilon === void 0) { epsilon = 0.01; }
  54895. var _this = this;
  54896. /**
  54897. * List of animations used by the particle system.
  54898. */
  54899. this.animations = [];
  54900. /**
  54901. * The rendering group used by the Particle system to chose when to render.
  54902. */
  54903. this.renderingGroupId = 0;
  54904. /**
  54905. * The emitter represents the Mesh or position we are attaching the particle system to.
  54906. */
  54907. this.emitter = null;
  54908. /**
  54909. * The maximum number of particles to emit per frame
  54910. */
  54911. this.emitRate = 10;
  54912. /**
  54913. * If you want to launch only a few particles at once, that can be done, as well.
  54914. */
  54915. this.manualEmitCount = -1;
  54916. /**
  54917. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  54918. */
  54919. this.updateSpeed = 0.01;
  54920. /**
  54921. * The amount of time the particle system is running (depends of the overall update speed).
  54922. */
  54923. this.targetStopDuration = 0;
  54924. /**
  54925. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  54926. */
  54927. this.disposeOnStop = false;
  54928. /**
  54929. * Minimum power of emitting particles.
  54930. */
  54931. this.minEmitPower = 1;
  54932. /**
  54933. * Maximum power of emitting particles.
  54934. */
  54935. this.maxEmitPower = 1;
  54936. /**
  54937. * Minimum life time of emitting particles.
  54938. */
  54939. this.minLifeTime = 1;
  54940. /**
  54941. * Maximum life time of emitting particles.
  54942. */
  54943. this.maxLifeTime = 1;
  54944. /**
  54945. * Minimum Size of emitting particles.
  54946. */
  54947. this.minSize = 1;
  54948. /**
  54949. * Maximum Size of emitting particles.
  54950. */
  54951. this.maxSize = 1;
  54952. /**
  54953. * Minimum scale of emitting particles on X axis.
  54954. */
  54955. this.minScaleX = 1;
  54956. /**
  54957. * Maximum scale of emitting particles on X axis.
  54958. */
  54959. this.maxScaleX = 1;
  54960. /**
  54961. * Minimum scale of emitting particles on Y axis.
  54962. */
  54963. this.minScaleY = 1;
  54964. /**
  54965. * Maximum scale of emitting particles on Y axis.
  54966. */
  54967. this.maxScaleY = 1;
  54968. /**
  54969. * Gets or sets the minimal initial rotation in radians.
  54970. */
  54971. this.minInitialRotation = 0;
  54972. /**
  54973. * Gets or sets the maximal initial rotation in radians.
  54974. */
  54975. this.maxInitialRotation = 0;
  54976. /**
  54977. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  54978. */
  54979. this.minAngularSpeed = 0;
  54980. /**
  54981. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  54982. */
  54983. this.maxAngularSpeed = 0;
  54984. /**
  54985. * The layer mask we are rendering the particles through.
  54986. */
  54987. this.layerMask = 0x0FFFFFFF;
  54988. /**
  54989. * This can help using your own shader to render the particle system.
  54990. * The according effect will be created
  54991. */
  54992. this.customShader = null;
  54993. /**
  54994. * By default particle system starts as soon as they are created. This prevents the
  54995. * automatic start to happen and let you decide when to start emitting particles.
  54996. */
  54997. this.preventAutoStart = false;
  54998. /**
  54999. * Callback triggered when the particle animation is ending.
  55000. */
  55001. this.onAnimationEnd = null;
  55002. /**
  55003. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55004. */
  55005. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55006. /**
  55007. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55008. * to override the particles.
  55009. */
  55010. this.forceDepthWrite = false;
  55011. /**
  55012. * You can use gravity if you want to give an orientation to your particles.
  55013. */
  55014. this.gravity = BABYLON.Vector3.Zero();
  55015. this._colorGradients = null;
  55016. this._sizeGradients = null;
  55017. /**
  55018. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55019. */
  55020. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55021. /**
  55022. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55023. */
  55024. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55025. /**
  55026. * Color the particle will have at the end of its lifetime
  55027. */
  55028. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55029. /**
  55030. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55031. */
  55032. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55033. /**
  55034. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not
  55035. */
  55036. this.spriteCellLoop = true;
  55037. /**
  55038. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop
  55039. */
  55040. this.spriteCellChangeSpeed = 0;
  55041. /**
  55042. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display
  55043. */
  55044. this.startSpriteCellID = 0;
  55045. /**
  55046. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display
  55047. */
  55048. this.endSpriteCellID = 0;
  55049. /**
  55050. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55051. */
  55052. this.spriteCellWidth = 0;
  55053. /**
  55054. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55055. */
  55056. this.spriteCellHeight = 0;
  55057. /** 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 */
  55058. this.preWarmCycles = 0;
  55059. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55060. this.preWarmStepOffset = 1;
  55061. /**
  55062. * An event triggered when the system is disposed
  55063. */
  55064. this.onDisposeObservable = new BABYLON.Observable();
  55065. this._particles = new Array();
  55066. this._stockParticles = new Array();
  55067. this._newPartsExcess = 0;
  55068. this._vertexBuffers = {};
  55069. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55070. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55071. this._scaledDirection = BABYLON.Vector3.Zero();
  55072. this._scaledGravity = BABYLON.Vector3.Zero();
  55073. this._currentRenderId = -1;
  55074. this._useInstancing = false;
  55075. this._started = false;
  55076. this._stopped = false;
  55077. this._actualFrame = 0;
  55078. this._isBillboardBased = true;
  55079. // start of sub system methods
  55080. /**
  55081. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55082. * Its lifetime will start back at 0.
  55083. */
  55084. this.recycleParticle = function (particle) {
  55085. var lastParticle = _this._particles.pop();
  55086. if (lastParticle !== particle) {
  55087. lastParticle.copyTo(particle);
  55088. }
  55089. _this._stockParticles.push(lastParticle);
  55090. };
  55091. this._createParticle = function () {
  55092. var particle;
  55093. if (_this._stockParticles.length !== 0) {
  55094. particle = _this._stockParticles.pop();
  55095. particle.age = 0;
  55096. particle.cellIndex = _this.startSpriteCellID;
  55097. }
  55098. else {
  55099. particle = new BABYLON.Particle(_this);
  55100. }
  55101. return particle;
  55102. };
  55103. this._emitFromParticle = function (particle) {
  55104. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55105. return;
  55106. }
  55107. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55108. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55109. subSystem._rootParticleSystem = _this;
  55110. _this.activeSubSystems.push(subSystem);
  55111. subSystem.start();
  55112. };
  55113. this.id = name;
  55114. this.name = name;
  55115. this._capacity = capacity;
  55116. this._epsilon = epsilon;
  55117. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55118. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55119. this._customEffect = customEffect;
  55120. scene.particleSystems.push(this);
  55121. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55122. this._createIndexBuffer();
  55123. this._createVertexBuffers();
  55124. // Default emitter type
  55125. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55126. this.updateFunction = function (particles) {
  55127. for (var index = 0; index < particles.length; index++) {
  55128. var particle = particles[index];
  55129. particle.age += _this._scaledUpdateSpeed;
  55130. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55131. _this._emitFromParticle(particle);
  55132. _this.recycleParticle(particle);
  55133. index--;
  55134. continue;
  55135. }
  55136. else {
  55137. var ratio = particle.age / particle.lifeTime;
  55138. // Color
  55139. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55140. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55141. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, particle.color);
  55142. });
  55143. }
  55144. else {
  55145. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55146. particle.color.addInPlace(_this._scaledColorStep);
  55147. if (particle.color.a < 0) {
  55148. particle.color.a = 0;
  55149. }
  55150. }
  55151. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55152. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55153. particle.position.addInPlace(_this._scaledDirection);
  55154. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55155. particle.direction.addInPlace(_this._scaledGravity);
  55156. // Gradient
  55157. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55158. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55159. particle.size = particle._initialSize * BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  55160. });
  55161. }
  55162. if (_this._isAnimationSheetEnabled) {
  55163. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55164. }
  55165. }
  55166. }
  55167. };
  55168. }
  55169. /**
  55170. * Gets the current list of color gradients.
  55171. * You must use addColorGradient and removeColorGradient to udpate this list
  55172. * @returns the list of color gradients
  55173. */
  55174. ParticleSystem.prototype.getColorGradients = function () {
  55175. return this._colorGradients;
  55176. };
  55177. /**
  55178. * Gets the current list of size gradients.
  55179. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55180. * @returns the list of size gradients
  55181. */
  55182. ParticleSystem.prototype.getSizeGradients = function () {
  55183. return this._sizeGradients;
  55184. };
  55185. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55186. /**
  55187. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55188. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55189. */
  55190. get: function () {
  55191. if (this.particleEmitterType.direction1) {
  55192. return this.particleEmitterType.direction1;
  55193. }
  55194. return BABYLON.Vector3.Zero();
  55195. },
  55196. set: function (value) {
  55197. if (this.particleEmitterType.direction1) {
  55198. this.particleEmitterType.direction1 = value;
  55199. }
  55200. },
  55201. enumerable: true,
  55202. configurable: true
  55203. });
  55204. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55205. /**
  55206. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55207. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55208. */
  55209. get: function () {
  55210. if (this.particleEmitterType.direction2) {
  55211. return this.particleEmitterType.direction2;
  55212. }
  55213. return BABYLON.Vector3.Zero();
  55214. },
  55215. set: function (value) {
  55216. if (this.particleEmitterType.direction2) {
  55217. this.particleEmitterType.direction2 = value;
  55218. }
  55219. },
  55220. enumerable: true,
  55221. configurable: true
  55222. });
  55223. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55224. /**
  55225. * 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.
  55226. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55227. */
  55228. get: function () {
  55229. if (this.particleEmitterType.minEmitBox) {
  55230. return this.particleEmitterType.minEmitBox;
  55231. }
  55232. return BABYLON.Vector3.Zero();
  55233. },
  55234. set: function (value) {
  55235. if (this.particleEmitterType.minEmitBox) {
  55236. this.particleEmitterType.minEmitBox = value;
  55237. }
  55238. },
  55239. enumerable: true,
  55240. configurable: true
  55241. });
  55242. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55243. /**
  55244. * 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.
  55245. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55246. */
  55247. get: function () {
  55248. if (this.particleEmitterType.maxEmitBox) {
  55249. return this.particleEmitterType.maxEmitBox;
  55250. }
  55251. return BABYLON.Vector3.Zero();
  55252. },
  55253. set: function (value) {
  55254. if (this.particleEmitterType.maxEmitBox) {
  55255. this.particleEmitterType.maxEmitBox = value;
  55256. }
  55257. },
  55258. enumerable: true,
  55259. configurable: true
  55260. });
  55261. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55262. /**
  55263. * Sets a callback that will be triggered when the system is disposed
  55264. */
  55265. set: function (callback) {
  55266. if (this._onDisposeObserver) {
  55267. this.onDisposeObservable.remove(this._onDisposeObserver);
  55268. }
  55269. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55270. },
  55271. enumerable: true,
  55272. configurable: true
  55273. });
  55274. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55275. /**
  55276. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55277. */
  55278. get: function () {
  55279. return this._isAnimationSheetEnabled;
  55280. },
  55281. enumerable: true,
  55282. configurable: true
  55283. });
  55284. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55285. /**
  55286. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55287. */
  55288. get: function () {
  55289. return this._isBillboardBased;
  55290. },
  55291. set: function (value) {
  55292. if (this._isBillboardBased === value) {
  55293. return;
  55294. }
  55295. this._isBillboardBased = value;
  55296. this._resetEffect();
  55297. },
  55298. enumerable: true,
  55299. configurable: true
  55300. });
  55301. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55302. //end of Sub-emitter
  55303. /**
  55304. * Gets the current list of active particles
  55305. */
  55306. get: function () {
  55307. return this._particles;
  55308. },
  55309. enumerable: true,
  55310. configurable: true
  55311. });
  55312. /**
  55313. * Returns the string "ParticleSystem"
  55314. * @returns a string containing the class name
  55315. */
  55316. ParticleSystem.prototype.getClassName = function () {
  55317. return "ParticleSystem";
  55318. };
  55319. /**
  55320. * Adds a new size gradient
  55321. * @param gradient defines the gradient to use (between 0 and 1)
  55322. * @param factor defines the size factor to affect to the specified gradient
  55323. */
  55324. ParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  55325. if (!this._sizeGradients) {
  55326. this._sizeGradients = [];
  55327. }
  55328. var sizeGradient = new BABYLON.FactorGradient();
  55329. sizeGradient.gradient = gradient;
  55330. sizeGradient.factor = factor;
  55331. this._sizeGradients.push(sizeGradient);
  55332. this._sizeGradients.sort(function (a, b) {
  55333. if (a.gradient < b.gradient) {
  55334. return -1;
  55335. }
  55336. else if (a.gradient > b.gradient) {
  55337. return 1;
  55338. }
  55339. return 0;
  55340. });
  55341. return this;
  55342. };
  55343. /**
  55344. * Remove a specific size gradient
  55345. * @param gradient defines the gradient to remove
  55346. */
  55347. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55348. if (!this._sizeGradients) {
  55349. return this;
  55350. }
  55351. var index = 0;
  55352. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  55353. var sizeGradient = _a[_i];
  55354. if (sizeGradient.gradient === gradient) {
  55355. this._sizeGradients.splice(index, 1);
  55356. break;
  55357. }
  55358. index++;
  55359. }
  55360. return this;
  55361. };
  55362. /**
  55363. * Adds a new color gradient
  55364. * @param gradient defines the gradient to use (between 0 and 1)
  55365. * @param color defines the color to affect to the specified gradient
  55366. */
  55367. ParticleSystem.prototype.addColorGradient = function (gradient, color) {
  55368. if (!this._colorGradients) {
  55369. this._colorGradients = [];
  55370. }
  55371. var colorGradient = new BABYLON.ColorGradient();
  55372. colorGradient.gradient = gradient;
  55373. colorGradient.color = color;
  55374. this._colorGradients.push(colorGradient);
  55375. this._colorGradients.sort(function (a, b) {
  55376. if (a.gradient < b.gradient) {
  55377. return -1;
  55378. }
  55379. else if (a.gradient > b.gradient) {
  55380. return 1;
  55381. }
  55382. return 0;
  55383. });
  55384. return this;
  55385. };
  55386. /**
  55387. * Remove a specific color gradient
  55388. * @param gradient defines the gradient to remove
  55389. */
  55390. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55391. if (!this._colorGradients) {
  55392. return this;
  55393. }
  55394. var index = 0;
  55395. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55396. var colorGradient = _a[_i];
  55397. if (colorGradient.gradient === gradient) {
  55398. this._colorGradients.splice(index, 1);
  55399. break;
  55400. }
  55401. index++;
  55402. }
  55403. return this;
  55404. };
  55405. ParticleSystem.prototype._resetEffect = function () {
  55406. if (this._vertexBuffer) {
  55407. this._vertexBuffer.dispose();
  55408. this._vertexBuffer = null;
  55409. }
  55410. if (this._spriteBuffer) {
  55411. this._spriteBuffer.dispose();
  55412. this._spriteBuffer = null;
  55413. }
  55414. this._createVertexBuffers();
  55415. };
  55416. ParticleSystem.prototype._createVertexBuffers = function () {
  55417. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55418. if (this._isAnimationSheetEnabled) {
  55419. this._vertexBufferSize += 1;
  55420. }
  55421. if (!this._isBillboardBased) {
  55422. this._vertexBufferSize += 3;
  55423. }
  55424. var engine = this._scene.getEngine();
  55425. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55426. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55427. var dataOffset = 0;
  55428. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55429. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55430. dataOffset += 3;
  55431. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55432. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55433. dataOffset += 4;
  55434. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55435. this._vertexBuffers["angle"] = options;
  55436. dataOffset += 1;
  55437. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55438. this._vertexBuffers["size"] = size;
  55439. dataOffset += 2;
  55440. if (this._isAnimationSheetEnabled) {
  55441. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55442. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55443. dataOffset += 1;
  55444. }
  55445. if (!this._isBillboardBased) {
  55446. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55447. this._vertexBuffers["direction"] = directionBuffer;
  55448. dataOffset += 3;
  55449. }
  55450. var offsets;
  55451. if (this._useInstancing) {
  55452. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55453. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55454. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55455. }
  55456. else {
  55457. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55458. dataOffset += 2;
  55459. }
  55460. this._vertexBuffers["offset"] = offsets;
  55461. };
  55462. ParticleSystem.prototype._createIndexBuffer = function () {
  55463. if (this._useInstancing) {
  55464. return;
  55465. }
  55466. var indices = [];
  55467. var index = 0;
  55468. for (var count = 0; count < this._capacity; count++) {
  55469. indices.push(index);
  55470. indices.push(index + 1);
  55471. indices.push(index + 2);
  55472. indices.push(index);
  55473. indices.push(index + 2);
  55474. indices.push(index + 3);
  55475. index += 4;
  55476. }
  55477. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55478. };
  55479. /**
  55480. * Gets the maximum number of particles active at the same time.
  55481. * @returns The max number of active particles.
  55482. */
  55483. ParticleSystem.prototype.getCapacity = function () {
  55484. return this._capacity;
  55485. };
  55486. /**
  55487. * Gets Wether there are still active particles in the system.
  55488. * @returns True if it is alive, otherwise false.
  55489. */
  55490. ParticleSystem.prototype.isAlive = function () {
  55491. return this._alive;
  55492. };
  55493. /**
  55494. * Gets Wether the system has been started.
  55495. * @returns True if it has been started, otherwise false.
  55496. */
  55497. ParticleSystem.prototype.isStarted = function () {
  55498. return this._started;
  55499. };
  55500. /**
  55501. * Starts the particle system and begins to emit.
  55502. */
  55503. ParticleSystem.prototype.start = function () {
  55504. this._started = true;
  55505. this._stopped = false;
  55506. this._actualFrame = 0;
  55507. if (this.subEmitters && this.subEmitters.length != 0) {
  55508. this.activeSubSystems = new Array();
  55509. }
  55510. if (this.preWarmCycles) {
  55511. for (var index = 0; index < this.preWarmCycles; index++) {
  55512. this.animate(true);
  55513. }
  55514. }
  55515. };
  55516. /**
  55517. * Stops the particle system.
  55518. * @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.
  55519. */
  55520. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55521. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55522. this._stopped = true;
  55523. if (stopSubEmitters) {
  55524. this._stopSubEmitters();
  55525. }
  55526. };
  55527. // animation sheet
  55528. /**
  55529. * Remove all active particles
  55530. */
  55531. ParticleSystem.prototype.reset = function () {
  55532. this._stockParticles = [];
  55533. this._particles = [];
  55534. };
  55535. /**
  55536. * @hidden (for internal use only)
  55537. */
  55538. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55539. var offset = index * this._vertexBufferSize;
  55540. this._vertexData[offset++] = particle.position.x;
  55541. this._vertexData[offset++] = particle.position.y;
  55542. this._vertexData[offset++] = particle.position.z;
  55543. this._vertexData[offset++] = particle.color.r;
  55544. this._vertexData[offset++] = particle.color.g;
  55545. this._vertexData[offset++] = particle.color.b;
  55546. this._vertexData[offset++] = particle.color.a;
  55547. this._vertexData[offset++] = particle.angle;
  55548. this._vertexData[offset++] = particle.scale.x * particle.size;
  55549. this._vertexData[offset++] = particle.scale.y * particle.size;
  55550. if (this._isAnimationSheetEnabled) {
  55551. this._vertexData[offset++] = particle.cellIndex;
  55552. }
  55553. if (!this._isBillboardBased) {
  55554. if (particle._initialDirection) {
  55555. this._vertexData[offset++] = particle._initialDirection.x;
  55556. this._vertexData[offset++] = particle._initialDirection.y;
  55557. this._vertexData[offset++] = particle._initialDirection.z;
  55558. }
  55559. else {
  55560. this._vertexData[offset++] = particle.direction.x;
  55561. this._vertexData[offset++] = particle.direction.y;
  55562. this._vertexData[offset++] = particle.direction.z;
  55563. }
  55564. }
  55565. if (!this._useInstancing) {
  55566. if (this._isAnimationSheetEnabled) {
  55567. if (offsetX === 0)
  55568. offsetX = this._epsilon;
  55569. else if (offsetX === 1)
  55570. offsetX = 1 - this._epsilon;
  55571. if (offsetY === 0)
  55572. offsetY = this._epsilon;
  55573. else if (offsetY === 1)
  55574. offsetY = 1 - this._epsilon;
  55575. }
  55576. this._vertexData[offset++] = offsetX;
  55577. this._vertexData[offset++] = offsetY;
  55578. }
  55579. };
  55580. ParticleSystem.prototype._stopSubEmitters = function () {
  55581. if (!this.activeSubSystems) {
  55582. return;
  55583. }
  55584. this.activeSubSystems.forEach(function (subSystem) {
  55585. subSystem.stop(true);
  55586. });
  55587. this.activeSubSystems = new Array();
  55588. };
  55589. ParticleSystem.prototype._removeFromRoot = function () {
  55590. if (!this._rootParticleSystem) {
  55591. return;
  55592. }
  55593. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55594. if (index !== -1) {
  55595. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55596. }
  55597. };
  55598. // end of sub system methods
  55599. ParticleSystem.prototype._update = function (newParticles) {
  55600. // Update current
  55601. this._alive = this._particles.length > 0;
  55602. this.updateFunction(this._particles);
  55603. // Add new ones
  55604. var worldMatrix;
  55605. if (this.emitter.position) {
  55606. var emitterMesh = this.emitter;
  55607. worldMatrix = emitterMesh.getWorldMatrix();
  55608. }
  55609. else {
  55610. var emitterPosition = this.emitter;
  55611. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55612. }
  55613. var particle;
  55614. for (var index = 0; index < newParticles; index++) {
  55615. if (this._particles.length === this._capacity) {
  55616. break;
  55617. }
  55618. particle = this._createParticle();
  55619. this._particles.push(particle);
  55620. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55621. if (this.startPositionFunction) {
  55622. this.startPositionFunction(worldMatrix, particle.position, particle);
  55623. }
  55624. else {
  55625. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55626. }
  55627. if (this.startDirectionFunction) {
  55628. this.startDirectionFunction(worldMatrix, particle.direction, particle);
  55629. }
  55630. else {
  55631. this.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55632. }
  55633. if (emitPower === 0) {
  55634. if (!particle._initialDirection) {
  55635. particle._initialDirection = particle.direction.clone();
  55636. }
  55637. else {
  55638. particle._initialDirection.copyFrom(particle.direction);
  55639. }
  55640. }
  55641. else {
  55642. particle._initialDirection = null;
  55643. }
  55644. particle.direction.scaleInPlace(emitPower);
  55645. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55646. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55647. particle._initialSize = particle.size;
  55648. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this.minScaleX, this.maxScaleX), BABYLON.Scalar.RandomRange(this.minScaleY, this.maxScaleY));
  55649. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55650. particle.angle = BABYLON.Scalar.RandomRange(this.minInitialRotation, this.maxInitialRotation);
  55651. if (!this._colorGradients || this._colorGradients.length === 0) {
  55652. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55653. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55654. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55655. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55656. }
  55657. else {
  55658. particle.color.copyFrom(this._colorGradients[0].color);
  55659. }
  55660. }
  55661. };
  55662. ParticleSystem.prototype._getEffect = function () {
  55663. if (this._customEffect) {
  55664. return this._customEffect;
  55665. }
  55666. ;
  55667. var defines = [];
  55668. if (this._scene.clipPlane) {
  55669. defines.push("#define CLIPPLANE");
  55670. }
  55671. if (this._isAnimationSheetEnabled) {
  55672. defines.push("#define ANIMATESHEET");
  55673. }
  55674. if (this._isBillboardBased) {
  55675. defines.push("#define BILLBOARD");
  55676. }
  55677. // Effect
  55678. var join = defines.join("\n");
  55679. if (this._cachedDefines !== join) {
  55680. this._cachedDefines = join;
  55681. var attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55682. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55683. if (this._isAnimationSheetEnabled) {
  55684. attributesNamesOrOptions.push("cellIndex");
  55685. effectCreationOption.push("particlesInfos");
  55686. }
  55687. if (!this._isBillboardBased) {
  55688. attributesNamesOrOptions.push("direction");
  55689. }
  55690. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55691. }
  55692. return this._effect;
  55693. };
  55694. /**
  55695. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55696. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55697. */
  55698. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55699. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55700. if (!this._started)
  55701. return;
  55702. if (!preWarmOnly) {
  55703. var effect = this._getEffect();
  55704. // Check
  55705. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55706. return;
  55707. if (this._currentRenderId === this._scene.getRenderId()) {
  55708. return;
  55709. }
  55710. this._currentRenderId = this._scene.getRenderId();
  55711. }
  55712. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55713. // determine the number of particles we need to create
  55714. var newParticles;
  55715. if (this.manualEmitCount > -1) {
  55716. newParticles = this.manualEmitCount;
  55717. this._newPartsExcess = 0;
  55718. this.manualEmitCount = 0;
  55719. }
  55720. else {
  55721. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55722. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55723. }
  55724. if (this._newPartsExcess > 1.0) {
  55725. newParticles += this._newPartsExcess >> 0;
  55726. this._newPartsExcess -= this._newPartsExcess >> 0;
  55727. }
  55728. this._alive = false;
  55729. if (!this._stopped) {
  55730. this._actualFrame += this._scaledUpdateSpeed;
  55731. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55732. this.stop();
  55733. }
  55734. else {
  55735. newParticles = 0;
  55736. }
  55737. this._update(newParticles);
  55738. // Stopped?
  55739. if (this._stopped) {
  55740. if (!this._alive) {
  55741. this._started = false;
  55742. if (this.onAnimationEnd) {
  55743. this.onAnimationEnd();
  55744. }
  55745. if (this.disposeOnStop) {
  55746. this._scene._toBeDisposed.push(this);
  55747. }
  55748. }
  55749. }
  55750. if (!preWarmOnly) {
  55751. // Update VBO
  55752. var offset = 0;
  55753. for (var index = 0; index < this._particles.length; index++) {
  55754. var particle = this._particles[index];
  55755. this._appendParticleVertices(offset, particle);
  55756. offset += this._useInstancing ? 1 : 4;
  55757. }
  55758. if (this._vertexBuffer) {
  55759. this._vertexBuffer.update(this._vertexData);
  55760. }
  55761. }
  55762. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55763. this.stop();
  55764. }
  55765. };
  55766. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55767. this._appendParticleVertex(offset++, particle, 0, 0);
  55768. if (!this._useInstancing) {
  55769. this._appendParticleVertex(offset++, particle, 1, 0);
  55770. this._appendParticleVertex(offset++, particle, 1, 1);
  55771. this._appendParticleVertex(offset++, particle, 0, 1);
  55772. }
  55773. };
  55774. /**
  55775. * Rebuilds the particle system.
  55776. */
  55777. ParticleSystem.prototype.rebuild = function () {
  55778. this._createIndexBuffer();
  55779. if (this._vertexBuffer) {
  55780. this._vertexBuffer._rebuild();
  55781. }
  55782. };
  55783. /**
  55784. * Is this system ready to be used/rendered
  55785. * @return true if the system is ready
  55786. */
  55787. ParticleSystem.prototype.isReady = function () {
  55788. var effect = this._getEffect();
  55789. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55790. return false;
  55791. }
  55792. return true;
  55793. };
  55794. /**
  55795. * Renders the particle system in its current state.
  55796. * @returns the current number of particles
  55797. */
  55798. ParticleSystem.prototype.render = function () {
  55799. var effect = this._getEffect();
  55800. // Check
  55801. if (!this.isReady() || !this._particles.length) {
  55802. return 0;
  55803. }
  55804. var engine = this._scene.getEngine();
  55805. // Render
  55806. engine.enableEffect(effect);
  55807. engine.setState(false);
  55808. var viewMatrix = this._scene.getViewMatrix();
  55809. effect.setTexture("diffuseSampler", this.particleTexture);
  55810. effect.setMatrix("view", viewMatrix);
  55811. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55812. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55813. var baseSize = this.particleTexture.getBaseSize();
  55814. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55815. }
  55816. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55817. if (this._scene.clipPlane) {
  55818. var clipPlane = this._scene.clipPlane;
  55819. var invView = viewMatrix.clone();
  55820. invView.invert();
  55821. effect.setMatrix("invView", invView);
  55822. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55823. }
  55824. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55825. // Draw order
  55826. switch (this.blendMode) {
  55827. case ParticleSystem.BLENDMODE_ADD:
  55828. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  55829. break;
  55830. case ParticleSystem.BLENDMODE_ONEONE:
  55831. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55832. break;
  55833. case ParticleSystem.BLENDMODE_STANDARD:
  55834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55835. break;
  55836. }
  55837. if (this.forceDepthWrite) {
  55838. engine.setDepthWrite(true);
  55839. }
  55840. if (this._useInstancing) {
  55841. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  55842. engine.unbindInstanceAttributes();
  55843. }
  55844. else {
  55845. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55846. }
  55847. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55848. return this._particles.length;
  55849. };
  55850. /**
  55851. * Disposes the particle system and free the associated resources
  55852. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55853. */
  55854. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55855. if (disposeTexture === void 0) { disposeTexture = true; }
  55856. if (this._vertexBuffer) {
  55857. this._vertexBuffer.dispose();
  55858. this._vertexBuffer = null;
  55859. }
  55860. if (this._spriteBuffer) {
  55861. this._spriteBuffer.dispose();
  55862. this._spriteBuffer = null;
  55863. }
  55864. if (this._indexBuffer) {
  55865. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55866. this._indexBuffer = null;
  55867. }
  55868. if (disposeTexture && this.particleTexture) {
  55869. this.particleTexture.dispose();
  55870. this.particleTexture = null;
  55871. }
  55872. this._removeFromRoot();
  55873. // Remove from scene
  55874. var index = this._scene.particleSystems.indexOf(this);
  55875. if (index > -1) {
  55876. this._scene.particleSystems.splice(index, 1);
  55877. }
  55878. // Callback
  55879. this.onDisposeObservable.notifyObservers(this);
  55880. this.onDisposeObservable.clear();
  55881. };
  55882. /**
  55883. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55884. * @param radius The radius of the sphere to emit from
  55885. * @returns the emitter
  55886. */
  55887. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55888. if (radius === void 0) { radius = 1; }
  55889. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55890. this.particleEmitterType = particleEmitter;
  55891. return particleEmitter;
  55892. };
  55893. /**
  55894. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55895. * @param radius The radius of the sphere to emit from
  55896. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55897. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55898. * @returns the emitter
  55899. */
  55900. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55901. if (radius === void 0) { radius = 1; }
  55902. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55903. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55904. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55905. this.particleEmitterType = particleEmitter;
  55906. return particleEmitter;
  55907. };
  55908. /**
  55909. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55910. * @param radius The radius of the cone to emit from
  55911. * @param angle The base angle of the cone
  55912. * @returns the emitter
  55913. */
  55914. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55915. if (radius === void 0) { radius = 1; }
  55916. if (angle === void 0) { angle = Math.PI / 4; }
  55917. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55918. this.particleEmitterType = particleEmitter;
  55919. return particleEmitter;
  55920. };
  55921. // this method needs to be changed when breaking changes will be allowed to match the sphere and cone methods and properties direction1,2 and minEmitBox,maxEmitBox to be removed from the system.
  55922. /**
  55923. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55924. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55925. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55926. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55927. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55928. * @returns the emitter
  55929. */
  55930. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55931. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55932. this.particleEmitterType = particleEmitter;
  55933. this.direction1 = direction1;
  55934. this.direction2 = direction2;
  55935. this.minEmitBox = minEmitBox;
  55936. this.maxEmitBox = maxEmitBox;
  55937. return particleEmitter;
  55938. };
  55939. // Clone
  55940. /**
  55941. * Clones the particle system.
  55942. * @param name The name of the cloned object
  55943. * @param newEmitter The new emitter to use
  55944. * @returns the cloned particle system
  55945. */
  55946. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55947. var custom = null;
  55948. var program = null;
  55949. if (this.customShader != null) {
  55950. program = this.customShader;
  55951. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55952. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55953. }
  55954. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55955. result.customShader = program;
  55956. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  55957. if (newEmitter === undefined) {
  55958. newEmitter = this.emitter;
  55959. }
  55960. result.emitter = newEmitter;
  55961. if (this.particleTexture) {
  55962. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  55963. }
  55964. if (!this.preventAutoStart) {
  55965. result.start();
  55966. }
  55967. return result;
  55968. };
  55969. /**
  55970. * Serializes the particle system to a JSON object.
  55971. * @returns the JSON object
  55972. */
  55973. ParticleSystem.prototype.serialize = function () {
  55974. var serializationObject = {};
  55975. ParticleSystem._Serialize(serializationObject, this);
  55976. serializationObject.textureMask = this.textureMask.asArray();
  55977. serializationObject.customShader = this.customShader;
  55978. serializationObject.preventAutoStart = this.preventAutoStart;
  55979. serializationObject.startSpriteCellID = this.startSpriteCellID;
  55980. serializationObject.endSpriteCellID = this.endSpriteCellID;
  55981. serializationObject.spriteCellLoop = this.spriteCellLoop;
  55982. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  55983. serializationObject.spriteCellWidth = this.spriteCellWidth;
  55984. serializationObject.spriteCellHeight = this.spriteCellHeight;
  55985. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  55986. return serializationObject;
  55987. };
  55988. /** @hidden */
  55989. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  55990. serializationObject.name = particleSystem.name;
  55991. serializationObject.id = particleSystem.id;
  55992. serializationObject.capacity = particleSystem.getCapacity();
  55993. // Emitter
  55994. if (particleSystem.emitter.position) {
  55995. var emitterMesh = particleSystem.emitter;
  55996. serializationObject.emitterId = emitterMesh.id;
  55997. }
  55998. else {
  55999. var emitterPosition = particleSystem.emitter;
  56000. serializationObject.emitter = emitterPosition.asArray();
  56001. }
  56002. // Emitter
  56003. if (particleSystem.particleEmitterType) {
  56004. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56005. }
  56006. if (particleSystem.particleTexture) {
  56007. serializationObject.textureName = particleSystem.particleTexture.name;
  56008. }
  56009. // Animations
  56010. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56011. // Particle system
  56012. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56013. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56014. serializationObject.minSize = particleSystem.minSize;
  56015. serializationObject.maxSize = particleSystem.maxSize;
  56016. serializationObject.minScaleX = particleSystem.minScaleX;
  56017. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56018. serializationObject.minScaleY = particleSystem.minScaleY;
  56019. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56020. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56021. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56022. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56023. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56024. serializationObject.emitRate = particleSystem.emitRate;
  56025. serializationObject.gravity = particleSystem.gravity.asArray();
  56026. serializationObject.color1 = particleSystem.color1.asArray();
  56027. serializationObject.color2 = particleSystem.color2.asArray();
  56028. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56029. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56030. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56031. serializationObject.blendMode = particleSystem.blendMode;
  56032. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56033. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56034. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56035. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56036. var colorGradients = particleSystem.getColorGradients();
  56037. if (colorGradients) {
  56038. serializationObject.colorGradients = [];
  56039. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56040. var colorGradient = colorGradients_1[_i];
  56041. serializationObject.colorGradients.push({
  56042. gradient: colorGradient.gradient,
  56043. color: colorGradient.color.asArray()
  56044. });
  56045. }
  56046. }
  56047. var sizeGradients = particleSystem.getSizeGradients();
  56048. if (sizeGradients) {
  56049. serializationObject.sizeGradients = [];
  56050. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56051. var sizeGradient = sizeGradients_1[_a];
  56052. serializationObject.sizeGradients.push({
  56053. gradient: sizeGradient.gradient,
  56054. factor: sizeGradient.factor
  56055. });
  56056. }
  56057. }
  56058. };
  56059. /** @hidden */
  56060. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56061. // Texture
  56062. if (parsedParticleSystem.textureName) {
  56063. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56064. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56065. }
  56066. // Emitter
  56067. if (parsedParticleSystem.emitterId) {
  56068. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56069. }
  56070. else {
  56071. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56072. }
  56073. // Animations
  56074. if (parsedParticleSystem.animations) {
  56075. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56076. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56077. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56078. }
  56079. }
  56080. if (parsedParticleSystem.autoAnimate) {
  56081. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56082. }
  56083. // Particle system
  56084. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56085. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56086. particleSystem.minSize = parsedParticleSystem.minSize;
  56087. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56088. if (parsedParticleSystem.minScaleX) {
  56089. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56090. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56091. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56092. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56093. }
  56094. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56095. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56096. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56097. }
  56098. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56099. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56100. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56101. }
  56102. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56103. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56104. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56105. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56106. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56107. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56108. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56109. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56110. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56111. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56112. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56113. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56114. if (parsedParticleSystem.colorGradients) {
  56115. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56116. var colorGradient = _a[_i];
  56117. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color));
  56118. }
  56119. }
  56120. if (parsedParticleSystem.sizeGradients) {
  56121. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56122. var sizeGradient = _c[_b];
  56123. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor);
  56124. }
  56125. }
  56126. // Emitter
  56127. if (parsedParticleSystem.particleEmitterType) {
  56128. var emitterType = void 0;
  56129. switch (parsedParticleSystem.particleEmitterType.type) {
  56130. case "SphereEmitter":
  56131. emitterType = new BABYLON.SphereParticleEmitter();
  56132. break;
  56133. case "SphereDirectedParticleEmitter":
  56134. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56135. break;
  56136. case "ConeEmitter":
  56137. emitterType = new BABYLON.ConeParticleEmitter();
  56138. break;
  56139. case "BoxEmitter":
  56140. default:
  56141. emitterType = new BABYLON.BoxParticleEmitter();
  56142. break;
  56143. }
  56144. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56145. particleSystem.particleEmitterType = emitterType;
  56146. }
  56147. };
  56148. /**
  56149. * Parses a JSON object to create a particle system.
  56150. * @param parsedParticleSystem The JSON object to parse
  56151. * @param scene The scene to create the particle system in
  56152. * @param rootUrl The root url to use to load external dependencies like texture
  56153. * @returns the Parsed particle system
  56154. */
  56155. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56156. var name = parsedParticleSystem.name;
  56157. var custom = null;
  56158. var program = null;
  56159. if (parsedParticleSystem.customShader) {
  56160. program = parsedParticleSystem.customShader;
  56161. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56162. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56163. }
  56164. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56165. particleSystem.customShader = program;
  56166. if (parsedParticleSystem.id) {
  56167. particleSystem.id = parsedParticleSystem.id;
  56168. }
  56169. // Auto start
  56170. if (parsedParticleSystem.preventAutoStart) {
  56171. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56172. }
  56173. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56174. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56175. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56176. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56177. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56178. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56179. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56180. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56181. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56182. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56183. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56184. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56185. if (!particleSystem.preventAutoStart) {
  56186. particleSystem.start();
  56187. }
  56188. return particleSystem;
  56189. };
  56190. /**
  56191. * Source color is added to the destination color without alpha affecting the result.
  56192. */
  56193. ParticleSystem.BLENDMODE_ONEONE = 0;
  56194. /**
  56195. * Blend current color and particle color using particle’s alpha.
  56196. */
  56197. ParticleSystem.BLENDMODE_STANDARD = 1;
  56198. /**
  56199. * Add current color and particle color multiplied by particle’s alpha.
  56200. */
  56201. ParticleSystem.BLENDMODE_ADD = 2;
  56202. return ParticleSystem;
  56203. }());
  56204. BABYLON.ParticleSystem = ParticleSystem;
  56205. })(BABYLON || (BABYLON = {}));
  56206. //# sourceMappingURL=babylon.particleSystem.js.map
  56207. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56208. var BABYLON;
  56209. (function (BABYLON) {
  56210. /**
  56211. * Particle emitter emitting particles from the inside of a box.
  56212. * It emits the particles randomly between 2 given directions.
  56213. */
  56214. var BoxParticleEmitter = /** @class */ (function () {
  56215. /**
  56216. * Creates a new instance BoxParticleEmitter
  56217. */
  56218. function BoxParticleEmitter() {
  56219. /**
  56220. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56221. */
  56222. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56223. /**
  56224. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56225. */
  56226. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56227. /**
  56228. * 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.
  56229. */
  56230. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56231. /**
  56232. * 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.
  56233. */
  56234. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56235. }
  56236. /**
  56237. * Called by the particle System when the direction is computed for the created particle.
  56238. * @param worldMatrix is the world matrix of the particle system
  56239. * @param directionToUpdate is the direction vector to update with the result
  56240. * @param particle is the particle we are computed the direction for
  56241. */
  56242. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56243. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56244. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56245. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56246. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56247. };
  56248. /**
  56249. * Called by the particle System when the position is computed for the created particle.
  56250. * @param worldMatrix is the world matrix of the particle system
  56251. * @param positionToUpdate is the position vector to update with the result
  56252. * @param particle is the particle we are computed the position for
  56253. */
  56254. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56255. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56256. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56257. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56258. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56259. };
  56260. /**
  56261. * Clones the current emitter and returns a copy of it
  56262. * @returns the new emitter
  56263. */
  56264. BoxParticleEmitter.prototype.clone = function () {
  56265. var newOne = new BoxParticleEmitter();
  56266. BABYLON.Tools.DeepCopy(this, newOne);
  56267. return newOne;
  56268. };
  56269. /**
  56270. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56271. * @param effect defines the update shader
  56272. */
  56273. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56274. effect.setVector3("direction1", this.direction1);
  56275. effect.setVector3("direction2", this.direction2);
  56276. effect.setVector3("minEmitBox", this.minEmitBox);
  56277. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56278. };
  56279. /**
  56280. * Returns a string to use to update the GPU particles update shader
  56281. * @returns a string containng the defines string
  56282. */
  56283. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56284. return "#define BOXEMITTER";
  56285. };
  56286. /**
  56287. * Returns the string "BoxEmitter"
  56288. * @returns a string containing the class name
  56289. */
  56290. BoxParticleEmitter.prototype.getClassName = function () {
  56291. return "BoxEmitter";
  56292. };
  56293. /**
  56294. * Serializes the particle system to a JSON object.
  56295. * @returns the JSON object
  56296. */
  56297. BoxParticleEmitter.prototype.serialize = function () {
  56298. var serializationObject = {};
  56299. serializationObject.type = this.getClassName();
  56300. serializationObject.direction1 = this.direction1.asArray();
  56301. serializationObject.direction2 = this.direction2.asArray();
  56302. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56303. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56304. return serializationObject;
  56305. };
  56306. /**
  56307. * Parse properties from a JSON object
  56308. * @param serializationObject defines the JSON object
  56309. */
  56310. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56311. this.direction1.copyFrom(serializationObject.direction1);
  56312. this.direction2.copyFrom(serializationObject.direction2);
  56313. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56314. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56315. };
  56316. return BoxParticleEmitter;
  56317. }());
  56318. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56319. })(BABYLON || (BABYLON = {}));
  56320. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56321. var BABYLON;
  56322. (function (BABYLON) {
  56323. /**
  56324. * Particle emitter emitting particles from the inside of a cone.
  56325. * It emits the particles alongside the cone volume from the base to the particle.
  56326. * The emission direction might be randomized.
  56327. */
  56328. var ConeParticleEmitter = /** @class */ (function () {
  56329. /**
  56330. * Creates a new instance ConeParticleEmitter
  56331. * @param radius the radius of the emission cone (1 by default)
  56332. * @param angles the cone base angle (PI by default)
  56333. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56334. */
  56335. function ConeParticleEmitter(radius, angle,
  56336. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56337. directionRandomizer) {
  56338. if (radius === void 0) { radius = 1; }
  56339. if (angle === void 0) { angle = Math.PI; }
  56340. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56341. this.directionRandomizer = directionRandomizer;
  56342. this.angle = angle;
  56343. this.radius = radius;
  56344. }
  56345. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56346. /**
  56347. * Gets or sets the radius of the emission cone
  56348. */
  56349. get: function () {
  56350. return this._radius;
  56351. },
  56352. set: function (value) {
  56353. this._radius = value;
  56354. this._buildHeight();
  56355. },
  56356. enumerable: true,
  56357. configurable: true
  56358. });
  56359. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56360. /**
  56361. * Gets or sets the angle of the emission cone
  56362. */
  56363. get: function () {
  56364. return this._angle;
  56365. },
  56366. set: function (value) {
  56367. this._angle = value;
  56368. this._buildHeight();
  56369. },
  56370. enumerable: true,
  56371. configurable: true
  56372. });
  56373. ConeParticleEmitter.prototype._buildHeight = function () {
  56374. if (this._angle !== 0) {
  56375. this._height = this._radius / Math.tan(this._angle / 2);
  56376. }
  56377. else {
  56378. this._height = 1;
  56379. }
  56380. };
  56381. /**
  56382. * Called by the particle System when the direction is computed for the created particle.
  56383. * @param worldMatrix is the world matrix of the particle system
  56384. * @param directionToUpdate is the direction vector to update with the result
  56385. * @param particle is the particle we are computed the direction for
  56386. */
  56387. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56388. if (this._angle === 0) {
  56389. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56390. }
  56391. else {
  56392. // measure the direction Vector from the emitter to the particle.
  56393. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56394. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56395. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56396. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56397. direction.x += randX;
  56398. direction.y += randY;
  56399. direction.z += randZ;
  56400. direction.normalize();
  56401. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56402. }
  56403. };
  56404. /**
  56405. * Called by the particle System when the position is computed for the created particle.
  56406. * @param worldMatrix is the world matrix of the particle system
  56407. * @param positionToUpdate is the position vector to update with the result
  56408. * @param particle is the particle we are computed the position for
  56409. */
  56410. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56411. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56412. var h = BABYLON.Scalar.RandomRange(0, 1);
  56413. // Better distribution in a cone at normal angles.
  56414. h = 1 - h * h;
  56415. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56416. radius = radius * h;
  56417. var randX = radius * Math.sin(s);
  56418. var randZ = radius * Math.cos(s);
  56419. var randY = h * this._height;
  56420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56421. };
  56422. /**
  56423. * Clones the current emitter and returns a copy of it
  56424. * @returns the new emitter
  56425. */
  56426. ConeParticleEmitter.prototype.clone = function () {
  56427. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56428. BABYLON.Tools.DeepCopy(this, newOne);
  56429. return newOne;
  56430. };
  56431. /**
  56432. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56433. * @param effect defines the update shader
  56434. */
  56435. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56436. effect.setFloat("radius", this._radius);
  56437. effect.setFloat("coneAngle", this._angle);
  56438. effect.setFloat("height", this._height);
  56439. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56440. };
  56441. /**
  56442. * Returns a string to use to update the GPU particles update shader
  56443. * @returns a string containng the defines string
  56444. */
  56445. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56446. return "#define CONEEMITTER";
  56447. };
  56448. /**
  56449. * Returns the string "BoxEmitter"
  56450. * @returns a string containing the class name
  56451. */
  56452. ConeParticleEmitter.prototype.getClassName = function () {
  56453. return "ConeEmitter";
  56454. };
  56455. /**
  56456. * Serializes the particle system to a JSON object.
  56457. * @returns the JSON object
  56458. */
  56459. ConeParticleEmitter.prototype.serialize = function () {
  56460. var serializationObject = {};
  56461. serializationObject.type = this.getClassName();
  56462. serializationObject.radius = this._radius;
  56463. serializationObject.angle = this._angle;
  56464. serializationObject.directionRandomizer = this.directionRandomizer;
  56465. return serializationObject;
  56466. };
  56467. /**
  56468. * Parse properties from a JSON object
  56469. * @param serializationObject defines the JSON object
  56470. */
  56471. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56472. this.radius = serializationObject.radius;
  56473. this.angle = serializationObject.angle;
  56474. this.directionRandomizer = serializationObject.directionRandomizer;
  56475. };
  56476. return ConeParticleEmitter;
  56477. }());
  56478. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56479. })(BABYLON || (BABYLON = {}));
  56480. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56481. var BABYLON;
  56482. (function (BABYLON) {
  56483. /**
  56484. * Particle emitter emitting particles from the inside of a sphere.
  56485. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56486. */
  56487. var SphereParticleEmitter = /** @class */ (function () {
  56488. /**
  56489. * Creates a new instance SphereParticleEmitter
  56490. * @param radius the radius of the emission sphere (1 by default)
  56491. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56492. */
  56493. function SphereParticleEmitter(
  56494. /**
  56495. * The radius of the emission sphere.
  56496. */
  56497. radius,
  56498. /**
  56499. * How much to randomize the particle direction [0-1].
  56500. */
  56501. directionRandomizer) {
  56502. if (radius === void 0) { radius = 1; }
  56503. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56504. this.radius = radius;
  56505. this.directionRandomizer = directionRandomizer;
  56506. /**
  56507. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56508. */
  56509. this.radiusRange = 1;
  56510. }
  56511. /**
  56512. * Called by the particle System when the direction is computed for the created particle.
  56513. * @param worldMatrix is the world matrix of the particle system
  56514. * @param directionToUpdate is the direction vector to update with the result
  56515. * @param particle is the particle we are computed the direction for
  56516. */
  56517. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56518. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56519. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56520. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56521. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56522. direction.x += randX;
  56523. direction.y += randY;
  56524. direction.z += randZ;
  56525. direction.normalize();
  56526. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56527. };
  56528. /**
  56529. * Called by the particle System when the position is computed for the created particle.
  56530. * @param worldMatrix is the world matrix of the particle system
  56531. * @param positionToUpdate is the position vector to update with the result
  56532. * @param particle is the particle we are computed the position for
  56533. */
  56534. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56535. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56536. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56537. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56538. var theta = Math.acos(2 * v - 1);
  56539. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56540. var randY = randRadius * Math.cos(theta);
  56541. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56542. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56543. };
  56544. /**
  56545. * Clones the current emitter and returns a copy of it
  56546. * @returns the new emitter
  56547. */
  56548. SphereParticleEmitter.prototype.clone = function () {
  56549. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56550. BABYLON.Tools.DeepCopy(this, newOne);
  56551. return newOne;
  56552. };
  56553. /**
  56554. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56555. * @param effect defines the update shader
  56556. */
  56557. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56558. effect.setFloat("radius", this.radius);
  56559. effect.setFloat("radiusRange", this.radiusRange);
  56560. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56561. };
  56562. /**
  56563. * Returns a string to use to update the GPU particles update shader
  56564. * @returns a string containng the defines string
  56565. */
  56566. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56567. return "#define SPHEREEMITTER";
  56568. };
  56569. /**
  56570. * Returns the string "SphereParticleEmitter"
  56571. * @returns a string containing the class name
  56572. */
  56573. SphereParticleEmitter.prototype.getClassName = function () {
  56574. return "SphereParticleEmitter";
  56575. };
  56576. /**
  56577. * Serializes the particle system to a JSON object.
  56578. * @returns the JSON object
  56579. */
  56580. SphereParticleEmitter.prototype.serialize = function () {
  56581. var serializationObject = {};
  56582. serializationObject.type = this.getClassName();
  56583. serializationObject.radius = this.radius;
  56584. serializationObject.directionRandomizer = this.directionRandomizer;
  56585. return serializationObject;
  56586. };
  56587. /**
  56588. * Parse properties from a JSON object
  56589. * @param serializationObject defines the JSON object
  56590. */
  56591. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56592. this.radius = serializationObject.radius;
  56593. this.directionRandomizer = serializationObject.directionRandomizer;
  56594. };
  56595. return SphereParticleEmitter;
  56596. }());
  56597. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56598. /**
  56599. * Particle emitter emitting particles from the inside of a sphere.
  56600. * It emits the particles randomly between two vectors.
  56601. */
  56602. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56603. __extends(SphereDirectedParticleEmitter, _super);
  56604. /**
  56605. * Creates a new instance SphereDirectedParticleEmitter
  56606. * @param radius the radius of the emission sphere (1 by default)
  56607. * @param direction1 the min limit of the emission direction (up vector by default)
  56608. * @param direction2 the max limit of the emission direction (up vector by default)
  56609. */
  56610. function SphereDirectedParticleEmitter(radius,
  56611. /**
  56612. * The min limit of the emission direction.
  56613. */
  56614. direction1,
  56615. /**
  56616. * The max limit of the emission direction.
  56617. */
  56618. direction2) {
  56619. if (radius === void 0) { radius = 1; }
  56620. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56621. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56622. var _this = _super.call(this, radius) || this;
  56623. _this.direction1 = direction1;
  56624. _this.direction2 = direction2;
  56625. return _this;
  56626. }
  56627. /**
  56628. * Called by the particle System when the direction is computed for the created particle.
  56629. * @param worldMatrix is the world matrix of the particle system
  56630. * @param directionToUpdate is the direction vector to update with the result
  56631. * @param particle is the particle we are computed the direction for
  56632. */
  56633. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56634. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56635. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56636. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56637. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56638. };
  56639. /**
  56640. * Clones the current emitter and returns a copy of it
  56641. * @returns the new emitter
  56642. */
  56643. SphereDirectedParticleEmitter.prototype.clone = function () {
  56644. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56645. BABYLON.Tools.DeepCopy(this, newOne);
  56646. return newOne;
  56647. };
  56648. /**
  56649. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56650. * @param effect defines the update shader
  56651. */
  56652. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56653. effect.setFloat("radius", this.radius);
  56654. effect.setFloat("radiusRange", this.radiusRange);
  56655. effect.setVector3("direction1", this.direction1);
  56656. effect.setVector3("direction2", this.direction2);
  56657. };
  56658. /**
  56659. * Returns a string to use to update the GPU particles update shader
  56660. * @returns a string containng the defines string
  56661. */
  56662. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56663. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56664. };
  56665. /**
  56666. * Returns the string "SphereDirectedParticleEmitter"
  56667. * @returns a string containing the class name
  56668. */
  56669. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56670. return "SphereDirectedParticleEmitter";
  56671. };
  56672. /**
  56673. * Serializes the particle system to a JSON object.
  56674. * @returns the JSON object
  56675. */
  56676. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56677. var serializationObject = _super.prototype.serialize.call(this);
  56678. serializationObject.direction1 = this.direction1.asArray();
  56679. serializationObject.direction2 = this.direction2.asArray();
  56680. return serializationObject;
  56681. };
  56682. /**
  56683. * Parse properties from a JSON object
  56684. * @param serializationObject defines the JSON object
  56685. */
  56686. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56687. _super.prototype.parse.call(this, serializationObject);
  56688. this.direction1.copyFrom(serializationObject.direction1);
  56689. this.direction2.copyFrom(serializationObject.direction2);
  56690. };
  56691. return SphereDirectedParticleEmitter;
  56692. }(SphereParticleEmitter));
  56693. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56694. })(BABYLON || (BABYLON = {}));
  56695. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56696. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56697. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56698. s = arguments[i];
  56699. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56700. t[p] = s[p];
  56701. }
  56702. return t;
  56703. };
  56704. var BABYLON;
  56705. (function (BABYLON) {
  56706. /**
  56707. * This represents a GPU particle system in Babylon
  56708. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56709. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56710. */
  56711. var GPUParticleSystem = /** @class */ (function () {
  56712. /**
  56713. * Instantiates a GPU particle system.
  56714. * 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.
  56715. * @param name The name of the particle system
  56716. * @param capacity The max number of particles alive at the same time
  56717. * @param scene The scene the particle system belongs to
  56718. */
  56719. function GPUParticleSystem(name, options, scene) {
  56720. /**
  56721. * The emitter represents the Mesh or position we are attaching the particle system to.
  56722. */
  56723. this.emitter = null;
  56724. /**
  56725. * The rendering group used by the Particle system to chose when to render.
  56726. */
  56727. this.renderingGroupId = 0;
  56728. /**
  56729. * The layer mask we are rendering the particles through.
  56730. */
  56731. this.layerMask = 0x0FFFFFFF;
  56732. this._accumulatedCount = 0;
  56733. this._targetIndex = 0;
  56734. this._currentRenderId = -1;
  56735. this._started = false;
  56736. this._stopped = false;
  56737. this._timeDelta = 0;
  56738. this._attributesStrideSize = 21;
  56739. this._actualFrame = 0;
  56740. /**
  56741. * List of animations used by the particle system.
  56742. */
  56743. this.animations = [];
  56744. /**
  56745. * An event triggered when the system is disposed.
  56746. */
  56747. this.onDisposeObservable = new BABYLON.Observable();
  56748. /**
  56749. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56750. */
  56751. this.updateSpeed = 0.01;
  56752. /**
  56753. * The amount of time the particle system is running (depends of the overall update speed).
  56754. */
  56755. this.targetStopDuration = 0;
  56756. /**
  56757. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56758. */
  56759. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56760. /**
  56761. * Minimum life time of emitting particles.
  56762. */
  56763. this.minLifeTime = 1;
  56764. /**
  56765. * Maximum life time of emitting particles.
  56766. */
  56767. this.maxLifeTime = 1;
  56768. /**
  56769. * Minimum Size of emitting particles.
  56770. */
  56771. this.minSize = 1;
  56772. /**
  56773. * Maximum Size of emitting particles.
  56774. */
  56775. this.maxSize = 1;
  56776. /**
  56777. * Minimum scale of emitting particles on X axis.
  56778. */
  56779. this.minScaleX = 1;
  56780. /**
  56781. * Maximum scale of emitting particles on X axis.
  56782. */
  56783. this.maxScaleX = 1;
  56784. /**
  56785. * Minimum scale of emitting particles on Y axis.
  56786. */
  56787. this.minScaleY = 1;
  56788. /**
  56789. * Maximum scale of emitting particles on Y axis.
  56790. */
  56791. this.maxScaleY = 1;
  56792. /**
  56793. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56794. */
  56795. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56796. /**
  56797. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56798. */
  56799. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56800. /**
  56801. * Color the particle will have at the end of its lifetime.
  56802. */
  56803. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56804. /**
  56805. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56806. */
  56807. this.emitRate = 100;
  56808. /**
  56809. * You can use gravity if you want to give an orientation to your particles.
  56810. */
  56811. this.gravity = BABYLON.Vector3.Zero();
  56812. /**
  56813. * Minimum power of emitting particles.
  56814. */
  56815. this.minEmitPower = 1;
  56816. /**
  56817. * Maximum power of emitting particles.
  56818. */
  56819. this.maxEmitPower = 1;
  56820. /**
  56821. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  56822. */
  56823. this.minAngularSpeed = 0;
  56824. /**
  56825. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  56826. */
  56827. this.maxAngularSpeed = 0;
  56828. /**
  56829. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56830. * to override the particles.
  56831. */
  56832. this.forceDepthWrite = false;
  56833. this._preWarmDone = false;
  56834. /** 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 */
  56835. this.preWarmCycles = 0;
  56836. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  56837. this.preWarmStepOffset = 1;
  56838. /**
  56839. * Gets or sets the minimal initial rotation in radians.
  56840. */
  56841. this.minInitialRotation = 0;
  56842. /**
  56843. * Gets or sets the maximal initial rotation in radians.
  56844. */
  56845. this.maxInitialRotation = 0;
  56846. this._isBillboardBased = true;
  56847. this._colorGradients = null;
  56848. this._sizeGradients = null;
  56849. this.id = name;
  56850. this.name = name;
  56851. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56852. this._engine = this._scene.getEngine();
  56853. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56854. var optionsAsNumber = options;
  56855. if (isFinite(optionsAsNumber)) {
  56856. fullOptions.capacity = optionsAsNumber;
  56857. }
  56858. this._capacity = fullOptions.capacity;
  56859. this._activeCount = fullOptions.capacity;
  56860. this._currentActiveCount = 0;
  56861. this._scene.particleSystems.push(this);
  56862. this._updateEffectOptions = {
  56863. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "initialSize"],
  56864. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  56865. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  56866. "angleRange", "radiusRange"],
  56867. uniformBuffersNames: [],
  56868. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  56869. defines: "",
  56870. fallbacks: null,
  56871. onCompiled: null,
  56872. onError: null,
  56873. indexParameters: null,
  56874. maxSimultaneousLights: 0,
  56875. transformFeedbackVaryings: []
  56876. };
  56877. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56878. // Random data
  56879. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56880. var d = [];
  56881. for (var i = 0; i < maxTextureSize; ++i) {
  56882. d.push(Math.random());
  56883. d.push(Math.random());
  56884. d.push(Math.random());
  56885. d.push(Math.random());
  56886. }
  56887. 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);
  56888. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56889. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56890. d = [];
  56891. for (var i = 0; i < maxTextureSize; ++i) {
  56892. d.push(Math.random());
  56893. d.push(Math.random());
  56894. d.push(Math.random());
  56895. d.push(Math.random());
  56896. }
  56897. 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);
  56898. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56899. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56900. this._randomTextureSize = maxTextureSize;
  56901. }
  56902. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56903. /**
  56904. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56905. */
  56906. get: function () {
  56907. if (!BABYLON.Engine.LastCreatedEngine) {
  56908. return false;
  56909. }
  56910. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56911. },
  56912. enumerable: true,
  56913. configurable: true
  56914. });
  56915. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56916. /**
  56917. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56918. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56919. */
  56920. get: function () {
  56921. if (this.particleEmitterType.direction1) {
  56922. return this.particleEmitterType.direction1;
  56923. }
  56924. return BABYLON.Vector3.Zero();
  56925. },
  56926. set: function (value) {
  56927. if (this.particleEmitterType.direction1) {
  56928. this.particleEmitterType.direction1 = value;
  56929. }
  56930. },
  56931. enumerable: true,
  56932. configurable: true
  56933. });
  56934. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56935. /**
  56936. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56937. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56938. */
  56939. get: function () {
  56940. if (this.particleEmitterType.direction2) {
  56941. return this.particleEmitterType.direction2;
  56942. }
  56943. return BABYLON.Vector3.Zero();
  56944. },
  56945. set: function (value) {
  56946. if (this.particleEmitterType.direction2) {
  56947. this.particleEmitterType.direction2 = value;
  56948. }
  56949. },
  56950. enumerable: true,
  56951. configurable: true
  56952. });
  56953. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56954. /**
  56955. * 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.
  56956. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56957. */
  56958. get: function () {
  56959. if (this.particleEmitterType.minEmitBox) {
  56960. return this.particleEmitterType.minEmitBox;
  56961. }
  56962. return BABYLON.Vector3.Zero();
  56963. },
  56964. set: function (value) {
  56965. if (this.particleEmitterType.minEmitBox) {
  56966. this.particleEmitterType.minEmitBox = value;
  56967. }
  56968. },
  56969. enumerable: true,
  56970. configurable: true
  56971. });
  56972. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56973. /**
  56974. * 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.
  56975. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56976. */
  56977. get: function () {
  56978. if (this.particleEmitterType.maxEmitBox) {
  56979. return this.particleEmitterType.maxEmitBox;
  56980. }
  56981. return BABYLON.Vector3.Zero();
  56982. },
  56983. set: function (value) {
  56984. if (this.particleEmitterType.maxEmitBox) {
  56985. this.particleEmitterType.maxEmitBox = value;
  56986. }
  56987. },
  56988. enumerable: true,
  56989. configurable: true
  56990. });
  56991. /**
  56992. * Gets the maximum number of particles active at the same time.
  56993. * @returns The max number of active particles.
  56994. */
  56995. GPUParticleSystem.prototype.getCapacity = function () {
  56996. return this._capacity;
  56997. };
  56998. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56999. /**
  57000. * Gets or set the number of active particles
  57001. */
  57002. get: function () {
  57003. return this._activeCount;
  57004. },
  57005. set: function (value) {
  57006. this._activeCount = Math.min(value, this._capacity);
  57007. },
  57008. enumerable: true,
  57009. configurable: true
  57010. });
  57011. /**
  57012. * Is this system ready to be used/rendered
  57013. * @return true if the system is ready
  57014. */
  57015. GPUParticleSystem.prototype.isReady = function () {
  57016. if (!this._updateEffect) {
  57017. this._recreateUpdateEffect();
  57018. this._recreateRenderEffect();
  57019. return false;
  57020. }
  57021. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57022. return false;
  57023. }
  57024. return true;
  57025. };
  57026. /**
  57027. * Gets Wether the system has been started.
  57028. * @returns True if it has been started, otherwise false.
  57029. */
  57030. GPUParticleSystem.prototype.isStarted = function () {
  57031. return this._started;
  57032. };
  57033. /**
  57034. * Starts the particle system and begins to emit.
  57035. */
  57036. GPUParticleSystem.prototype.start = function () {
  57037. this._started = true;
  57038. this._stopped = false;
  57039. this._preWarmDone = false;
  57040. };
  57041. /**
  57042. * Stops the particle system.
  57043. */
  57044. GPUParticleSystem.prototype.stop = function () {
  57045. this._stopped = true;
  57046. };
  57047. /**
  57048. * Remove all active particles
  57049. */
  57050. GPUParticleSystem.prototype.reset = function () {
  57051. this._releaseBuffers();
  57052. this._releaseVAOs();
  57053. this._currentActiveCount = 0;
  57054. this._targetIndex = 0;
  57055. };
  57056. /**
  57057. * Returns the string "GPUParticleSystem"
  57058. * @returns a string containing the class name
  57059. */
  57060. GPUParticleSystem.prototype.getClassName = function () {
  57061. return "GPUParticleSystem";
  57062. };
  57063. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57064. /**
  57065. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57066. */
  57067. get: function () {
  57068. return this._isBillboardBased;
  57069. },
  57070. set: function (value) {
  57071. if (this._isBillboardBased === value) {
  57072. return;
  57073. }
  57074. this._isBillboardBased = value;
  57075. this._releaseBuffers();
  57076. },
  57077. enumerable: true,
  57078. configurable: true
  57079. });
  57080. /**
  57081. * Gets the current list of color gradients.
  57082. * You must use addColorGradient and removeColorGradient to udpate this list
  57083. * @returns the list of color gradients
  57084. */
  57085. GPUParticleSystem.prototype.getColorGradients = function () {
  57086. return this._colorGradients;
  57087. };
  57088. /**
  57089. * Gets the current list of size gradients.
  57090. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57091. * @returns the list of size gradients
  57092. */
  57093. GPUParticleSystem.prototype.getSizeGradients = function () {
  57094. return this._sizeGradients;
  57095. };
  57096. /**
  57097. * Adds a new color gradient
  57098. * @param gradient defines the gradient to use (between 0 and 1)
  57099. * @param color defines the color to affect to the specified gradient
  57100. */
  57101. GPUParticleSystem.prototype.addColorGradient = function (gradient, color) {
  57102. if (!this._colorGradients) {
  57103. this._colorGradients = [];
  57104. }
  57105. var colorGradient = new BABYLON.ColorGradient();
  57106. colorGradient.gradient = gradient;
  57107. colorGradient.color = color;
  57108. this._colorGradients.push(colorGradient);
  57109. this._colorGradients.sort(function (a, b) {
  57110. if (a.gradient < b.gradient) {
  57111. return -1;
  57112. }
  57113. else if (a.gradient > b.gradient) {
  57114. return 1;
  57115. }
  57116. return 0;
  57117. });
  57118. if (this._colorGradientsTexture) {
  57119. this._colorGradientsTexture.dispose();
  57120. this._colorGradientsTexture = null;
  57121. }
  57122. this._releaseBuffers();
  57123. return this;
  57124. };
  57125. /**
  57126. * Remove a specific color gradient
  57127. * @param gradient defines the gradient to remove
  57128. */
  57129. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57130. if (!this._colorGradients) {
  57131. return this;
  57132. }
  57133. var index = 0;
  57134. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57135. var colorGradient = _a[_i];
  57136. if (colorGradient.gradient === gradient) {
  57137. this._colorGradients.splice(index, 1);
  57138. break;
  57139. }
  57140. index++;
  57141. }
  57142. if (this._colorGradientsTexture) {
  57143. this._colorGradientsTexture.dispose();
  57144. this._colorGradientsTexture = null;
  57145. }
  57146. this._releaseBuffers();
  57147. return this;
  57148. };
  57149. /**
  57150. * Adds a new size gradient
  57151. * @param gradient defines the gradient to use (between 0 and 1)
  57152. * @param factor defines the size factor to affect to the specified gradient
  57153. */
  57154. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57155. if (!this._sizeGradients) {
  57156. this._sizeGradients = [];
  57157. }
  57158. var sizeGradient = new BABYLON.FactorGradient();
  57159. sizeGradient.gradient = gradient;
  57160. sizeGradient.factor = factor;
  57161. this._sizeGradients.push(sizeGradient);
  57162. this._sizeGradients.sort(function (a, b) {
  57163. if (a.gradient < b.gradient) {
  57164. return -1;
  57165. }
  57166. else if (a.gradient > b.gradient) {
  57167. return 1;
  57168. }
  57169. return 0;
  57170. });
  57171. if (this._sizeGradientsTexture) {
  57172. this._sizeGradientsTexture.dispose();
  57173. this._sizeGradientsTexture = null;
  57174. }
  57175. this._releaseBuffers();
  57176. return this;
  57177. };
  57178. /**
  57179. * Remove a specific size gradient
  57180. * @param gradient defines the gradient to remove
  57181. */
  57182. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57183. if (!this._sizeGradients) {
  57184. return this;
  57185. }
  57186. var index = 0;
  57187. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57188. var sizeGradient = _a[_i];
  57189. if (sizeGradient.gradient === gradient) {
  57190. this._sizeGradients.splice(index, 1);
  57191. break;
  57192. }
  57193. index++;
  57194. }
  57195. if (this._sizeGradientsTexture) {
  57196. this._sizeGradientsTexture.dispose();
  57197. this._sizeGradientsTexture = null;
  57198. }
  57199. this._releaseBuffers();
  57200. return this;
  57201. };
  57202. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57203. var updateVertexBuffers = {};
  57204. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57205. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57206. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57207. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57208. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57209. var offset = 12;
  57210. if (this._sizeGradientsTexture) {
  57211. updateVertexBuffers["initialSize"] = source.createVertexBuffer("initialSize", offset, 3);
  57212. offset += 3;
  57213. }
  57214. if (!this._colorGradientsTexture) {
  57215. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57216. offset += 4;
  57217. }
  57218. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57219. offset += 3;
  57220. if (!this._isBillboardBased) {
  57221. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57222. offset += 3;
  57223. }
  57224. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57225. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57226. this._engine.bindArrayBuffer(null);
  57227. return vao;
  57228. };
  57229. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57230. var renderVertexBuffers = {};
  57231. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57232. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57233. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57234. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57235. var offset = 12;
  57236. if (this._sizeGradientsTexture) {
  57237. offset += 3;
  57238. }
  57239. if (!this._colorGradientsTexture) {
  57240. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57241. offset += 4;
  57242. }
  57243. offset += 3; // Direction
  57244. if (!this._isBillboardBased) {
  57245. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57246. offset += 3;
  57247. }
  57248. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57249. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57250. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57251. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57252. this._engine.bindArrayBuffer(null);
  57253. return vao;
  57254. };
  57255. GPUParticleSystem.prototype._initialize = function (force) {
  57256. if (force === void 0) { force = false; }
  57257. if (this._buffer0 && !force) {
  57258. return;
  57259. }
  57260. var engine = this._scene.getEngine();
  57261. var data = new Array();
  57262. if (!this.isBillboardBased) {
  57263. this._attributesStrideSize += 3;
  57264. }
  57265. if (this._colorGradientsTexture) {
  57266. this._attributesStrideSize -= 4;
  57267. }
  57268. if (this._sizeGradientsTexture) {
  57269. this._attributesStrideSize += 3;
  57270. }
  57271. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57272. // position
  57273. data.push(0.0);
  57274. data.push(0.0);
  57275. data.push(0.0);
  57276. // Age and life
  57277. data.push(0.0); // create the particle as a dead one to create a new one at start
  57278. data.push(0.0);
  57279. // Seed
  57280. data.push(Math.random());
  57281. data.push(Math.random());
  57282. data.push(Math.random());
  57283. data.push(Math.random());
  57284. // Size
  57285. data.push(0.0);
  57286. data.push(0.0);
  57287. data.push(0.0);
  57288. if (this._sizeGradientsTexture) {
  57289. data.push(0.0);
  57290. data.push(0.0);
  57291. data.push(0.0);
  57292. }
  57293. if (!this._colorGradientsTexture) {
  57294. // color
  57295. data.push(0.0);
  57296. data.push(0.0);
  57297. data.push(0.0);
  57298. data.push(0.0);
  57299. }
  57300. // direction
  57301. data.push(0.0);
  57302. data.push(0.0);
  57303. data.push(0.0);
  57304. if (!this.isBillboardBased) {
  57305. // initialDirection
  57306. data.push(0.0);
  57307. data.push(0.0);
  57308. data.push(0.0);
  57309. }
  57310. // angle
  57311. data.push(0.0);
  57312. data.push(0.0);
  57313. }
  57314. // Sprite data
  57315. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57316. -0.5, 0.5, 0, 1,
  57317. -0.5, -0.5, 0, 0,
  57318. 0.5, -0.5, 1, 0]);
  57319. // Buffers
  57320. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57321. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57322. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57323. // Update VAO
  57324. this._updateVAO = [];
  57325. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57326. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57327. // Render VAO
  57328. this._renderVAO = [];
  57329. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57330. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57331. // Links
  57332. this._sourceBuffer = this._buffer0;
  57333. this._targetBuffer = this._buffer1;
  57334. };
  57335. /** @hidden */
  57336. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57337. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57338. if (this._isBillboardBased) {
  57339. defines += "\n#define BILLBOARD";
  57340. }
  57341. if (this._colorGradientsTexture) {
  57342. defines += "\n#define COLORGRADIENTS";
  57343. }
  57344. if (this._sizeGradientsTexture) {
  57345. defines += "\n#define SIZEGRADIENTS";
  57346. }
  57347. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57348. return;
  57349. }
  57350. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57351. if (this._sizeGradientsTexture) {
  57352. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialSize");
  57353. }
  57354. if (!this._colorGradientsTexture) {
  57355. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57356. }
  57357. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57358. if (!this._isBillboardBased) {
  57359. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57360. }
  57361. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57362. this._updateEffectOptions.defines = defines;
  57363. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57364. };
  57365. /** @hidden */
  57366. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57367. var defines = "";
  57368. if (this._scene.clipPlane) {
  57369. defines = "\n#define CLIPPLANE";
  57370. }
  57371. if (this._isBillboardBased) {
  57372. defines += "\n#define BILLBOARD";
  57373. }
  57374. if (this._colorGradientsTexture) {
  57375. defines += "\n#define COLORGRADIENTS";
  57376. }
  57377. if (this._renderEffect && this._renderEffect.defines === defines) {
  57378. return;
  57379. }
  57380. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57381. };
  57382. /**
  57383. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57384. * @param preWarm defines if we are in the pre-warmimg phase
  57385. */
  57386. GPUParticleSystem.prototype.animate = function (preWarm) {
  57387. if (preWarm === void 0) { preWarm = false; }
  57388. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57389. this._actualFrame += this._timeDelta;
  57390. if (!this._stopped) {
  57391. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57392. this.stop();
  57393. }
  57394. }
  57395. };
  57396. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57397. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57398. return;
  57399. }
  57400. var textureWidth = 256;
  57401. var data = new Float32Array(textureWidth);
  57402. for (var x = 0; x < textureWidth; x++) {
  57403. var ratio = x / textureWidth;
  57404. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57405. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor, nextGradient.factor, scale);
  57406. });
  57407. }
  57408. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57409. };
  57410. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57411. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57412. return;
  57413. }
  57414. var textureWidth = 256;
  57415. var data = new Uint8Array(textureWidth * 4);
  57416. var tmpColor = BABYLON.Tmp.Color4[0];
  57417. for (var x = 0; x < textureWidth; x++) {
  57418. var ratio = x / textureWidth;
  57419. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57420. BABYLON.Color4.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  57421. data[x * 4] = tmpColor.r * 255;
  57422. data[x * 4 + 1] = tmpColor.g * 255;
  57423. data[x * 4 + 2] = tmpColor.b * 255;
  57424. data[x * 4 + 3] = tmpColor.a * 255;
  57425. });
  57426. }
  57427. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57428. };
  57429. /**
  57430. * Renders the particle system in its current state
  57431. * @param preWarm defines if the system should only update the particles but not render them
  57432. * @returns the current number of particles
  57433. */
  57434. GPUParticleSystem.prototype.render = function (preWarm) {
  57435. if (preWarm === void 0) { preWarm = false; }
  57436. if (!this._started) {
  57437. return 0;
  57438. }
  57439. this._createColorGradientTexture();
  57440. this._createSizeGradientTexture();
  57441. this._recreateUpdateEffect();
  57442. this._recreateRenderEffect();
  57443. if (!this.isReady()) {
  57444. return 0;
  57445. }
  57446. if (!preWarm) {
  57447. if (!this._preWarmDone && this.preWarmCycles) {
  57448. for (var index = 0; index < this.preWarmCycles; index++) {
  57449. this.animate(true);
  57450. this.render(true);
  57451. }
  57452. this._preWarmDone = true;
  57453. }
  57454. if (this._currentRenderId === this._scene.getRenderId()) {
  57455. return 0;
  57456. }
  57457. this._currentRenderId = this._scene.getRenderId();
  57458. }
  57459. // Get everything ready to render
  57460. this._initialize();
  57461. this._accumulatedCount += this.emitRate * this._timeDelta;
  57462. if (this._accumulatedCount > 1) {
  57463. var intPart = this._accumulatedCount | 0;
  57464. this._accumulatedCount -= intPart;
  57465. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57466. }
  57467. if (!this._currentActiveCount) {
  57468. return 0;
  57469. }
  57470. // Enable update effect
  57471. this._engine.enableEffect(this._updateEffect);
  57472. this._engine.setState(false);
  57473. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57474. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57475. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57476. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57477. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57478. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57479. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57480. if (!this._colorGradientsTexture) {
  57481. this._updateEffect.setDirectColor4("color1", this.color1);
  57482. this._updateEffect.setDirectColor4("color2", this.color2);
  57483. }
  57484. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57485. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57486. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57487. this._updateEffect.setVector3("gravity", this.gravity);
  57488. if (this._sizeGradientsTexture) {
  57489. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57490. }
  57491. if (this.particleEmitterType) {
  57492. this.particleEmitterType.applyToShader(this._updateEffect);
  57493. }
  57494. var emitterWM;
  57495. if (this.emitter.position) {
  57496. var emitterMesh = this.emitter;
  57497. emitterWM = emitterMesh.getWorldMatrix();
  57498. }
  57499. else {
  57500. var emitterPosition = this.emitter;
  57501. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57502. }
  57503. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57504. // Bind source VAO
  57505. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57506. // Update
  57507. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57508. this._engine.setRasterizerState(false);
  57509. this._engine.beginTransformFeedback();
  57510. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57511. this._engine.endTransformFeedback();
  57512. this._engine.setRasterizerState(true);
  57513. this._engine.bindTransformFeedbackBuffer(null);
  57514. if (!preWarm) {
  57515. // Enable render effect
  57516. this._engine.enableEffect(this._renderEffect);
  57517. var viewMatrix = this._scene.getViewMatrix();
  57518. this._renderEffect.setMatrix("view", viewMatrix);
  57519. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57520. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57521. if (this._colorGradientsTexture) {
  57522. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57523. }
  57524. else {
  57525. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57526. }
  57527. if (this._scene.clipPlane) {
  57528. var clipPlane = this._scene.clipPlane;
  57529. var invView = viewMatrix.clone();
  57530. invView.invert();
  57531. this._renderEffect.setMatrix("invView", invView);
  57532. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57533. }
  57534. // Draw order
  57535. switch (this.blendMode) {
  57536. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57537. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57538. break;
  57539. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57540. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57541. break;
  57542. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57543. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57544. break;
  57545. }
  57546. if (this.forceDepthWrite) {
  57547. this._engine.setDepthWrite(true);
  57548. }
  57549. // Bind source VAO
  57550. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57551. // Render
  57552. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57553. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57554. }
  57555. // Switch VAOs
  57556. this._targetIndex++;
  57557. if (this._targetIndex === 2) {
  57558. this._targetIndex = 0;
  57559. }
  57560. // Switch buffers
  57561. var tmpBuffer = this._sourceBuffer;
  57562. this._sourceBuffer = this._targetBuffer;
  57563. this._targetBuffer = tmpBuffer;
  57564. return this._currentActiveCount;
  57565. };
  57566. /**
  57567. * Rebuilds the particle system
  57568. */
  57569. GPUParticleSystem.prototype.rebuild = function () {
  57570. this._initialize(true);
  57571. };
  57572. GPUParticleSystem.prototype._releaseBuffers = function () {
  57573. if (this._buffer0) {
  57574. this._buffer0.dispose();
  57575. this._buffer0 = null;
  57576. }
  57577. if (this._buffer1) {
  57578. this._buffer1.dispose();
  57579. this._buffer1 = null;
  57580. }
  57581. if (this._spriteBuffer) {
  57582. this._spriteBuffer.dispose();
  57583. this._spriteBuffer = null;
  57584. }
  57585. };
  57586. GPUParticleSystem.prototype._releaseVAOs = function () {
  57587. if (!this._updateVAO) {
  57588. return;
  57589. }
  57590. for (var index = 0; index < this._updateVAO.length; index++) {
  57591. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57592. }
  57593. this._updateVAO = [];
  57594. for (var index = 0; index < this._renderVAO.length; index++) {
  57595. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57596. }
  57597. this._renderVAO = [];
  57598. };
  57599. /**
  57600. * Disposes the particle system and free the associated resources
  57601. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57602. */
  57603. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57604. if (disposeTexture === void 0) { disposeTexture = true; }
  57605. var index = this._scene.particleSystems.indexOf(this);
  57606. if (index > -1) {
  57607. this._scene.particleSystems.splice(index, 1);
  57608. }
  57609. this._releaseBuffers();
  57610. this._releaseVAOs();
  57611. if (this._colorGradientsTexture) {
  57612. this._colorGradientsTexture.dispose();
  57613. this._colorGradientsTexture = null;
  57614. }
  57615. if (this._sizeGradientsTexture) {
  57616. this._sizeGradientsTexture.dispose();
  57617. this._sizeGradientsTexture = null;
  57618. }
  57619. if (this._randomTexture) {
  57620. this._randomTexture.dispose();
  57621. this._randomTexture = null;
  57622. }
  57623. if (this._randomTexture2) {
  57624. this._randomTexture2.dispose();
  57625. this._randomTexture2 = null;
  57626. }
  57627. if (disposeTexture && this.particleTexture) {
  57628. this.particleTexture.dispose();
  57629. this.particleTexture = null;
  57630. }
  57631. // Callback
  57632. this.onDisposeObservable.notifyObservers(this);
  57633. this.onDisposeObservable.clear();
  57634. };
  57635. /**
  57636. * Clones the particle system.
  57637. * @param name The name of the cloned object
  57638. * @param newEmitter The new emitter to use
  57639. * @returns the cloned particle system
  57640. */
  57641. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57642. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57643. BABYLON.Tools.DeepCopy(this, result);
  57644. if (newEmitter === undefined) {
  57645. newEmitter = this.emitter;
  57646. }
  57647. result.emitter = newEmitter;
  57648. if (this.particleTexture) {
  57649. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57650. }
  57651. return result;
  57652. };
  57653. /**
  57654. * Serializes the particle system to a JSON object.
  57655. * @returns the JSON object
  57656. */
  57657. GPUParticleSystem.prototype.serialize = function () {
  57658. var serializationObject = {};
  57659. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57660. return serializationObject;
  57661. };
  57662. /**
  57663. * Parses a JSON object to create a GPU particle system.
  57664. * @param parsedParticleSystem The JSON object to parse
  57665. * @param scene The scene to create the particle system in
  57666. * @param rootUrl The root url to use to load external dependencies like texture
  57667. * @returns the parsed GPU particle system
  57668. */
  57669. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57670. var name = parsedParticleSystem.name;
  57671. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57672. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57673. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57674. return particleSystem;
  57675. };
  57676. return GPUParticleSystem;
  57677. }());
  57678. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57679. })(BABYLON || (BABYLON = {}));
  57680. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57681. var BABYLON;
  57682. (function (BABYLON) {
  57683. /**
  57684. * Represents one particle of a solid particle system.
  57685. */
  57686. var SolidParticle = /** @class */ (function () {
  57687. /**
  57688. * Creates a Solid Particle object.
  57689. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57690. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57691. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57692. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57693. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57694. * @param shapeId (integer) is the model shape identifier in the SPS.
  57695. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57696. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57697. */
  57698. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57699. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57700. /**
  57701. * particle global index
  57702. */
  57703. this.idx = 0;
  57704. /**
  57705. * The color of the particle
  57706. */
  57707. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57708. /**
  57709. * The world space position of the particle.
  57710. */
  57711. this.position = BABYLON.Vector3.Zero();
  57712. /**
  57713. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57714. */
  57715. this.rotation = BABYLON.Vector3.Zero();
  57716. /**
  57717. * The scaling of the particle.
  57718. */
  57719. this.scaling = BABYLON.Vector3.One();
  57720. /**
  57721. * The uvs of the particle.
  57722. */
  57723. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57724. /**
  57725. * The current speed of the particle.
  57726. */
  57727. this.velocity = BABYLON.Vector3.Zero();
  57728. /**
  57729. * The pivot point in the particle local space.
  57730. */
  57731. this.pivot = BABYLON.Vector3.Zero();
  57732. /**
  57733. * Must the particle be translated from its pivot point in its local space ?
  57734. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57735. * Default : false
  57736. */
  57737. this.translateFromPivot = false;
  57738. /**
  57739. * Is the particle active or not ?
  57740. */
  57741. this.alive = true;
  57742. /**
  57743. * Is the particle visible or not ?
  57744. */
  57745. this.isVisible = true;
  57746. /**
  57747. * Index of this particle in the global "positions" array (Internal use)
  57748. */
  57749. this._pos = 0;
  57750. /**
  57751. * Index of this particle in the global "indices" array (Internal use)
  57752. */
  57753. this._ind = 0;
  57754. /**
  57755. * ModelShape id of this particle
  57756. */
  57757. this.shapeId = 0;
  57758. /**
  57759. * Index of the particle in its shape id (Internal use)
  57760. */
  57761. this.idxInShape = 0;
  57762. /**
  57763. * Still set as invisible in order to skip useless computations (Internal use)
  57764. */
  57765. this._stillInvisible = false;
  57766. /**
  57767. * Last computed particle rotation matrix
  57768. */
  57769. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57770. /**
  57771. * Parent particle Id, if any.
  57772. * Default null.
  57773. */
  57774. this.parentId = null;
  57775. /**
  57776. * Internal global position in the SPS.
  57777. */
  57778. this._globalPosition = BABYLON.Vector3.Zero();
  57779. this.idx = particleIndex;
  57780. this._pos = positionIndex;
  57781. this._ind = indiceIndex;
  57782. this._model = model;
  57783. this.shapeId = shapeId;
  57784. this.idxInShape = idxInShape;
  57785. this._sps = sps;
  57786. if (modelBoundingInfo) {
  57787. this._modelBoundingInfo = modelBoundingInfo;
  57788. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57789. }
  57790. }
  57791. Object.defineProperty(SolidParticle.prototype, "scale", {
  57792. /**
  57793. * Legacy support, changed scale to scaling
  57794. */
  57795. get: function () {
  57796. return this.scaling;
  57797. },
  57798. /**
  57799. * Legacy support, changed scale to scaling
  57800. */
  57801. set: function (scale) {
  57802. this.scaling = scale;
  57803. },
  57804. enumerable: true,
  57805. configurable: true
  57806. });
  57807. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57808. /**
  57809. * Legacy support, changed quaternion to rotationQuaternion
  57810. */
  57811. get: function () {
  57812. return this.rotationQuaternion;
  57813. },
  57814. /**
  57815. * Legacy support, changed quaternion to rotationQuaternion
  57816. */
  57817. set: function (q) {
  57818. this.rotationQuaternion = q;
  57819. },
  57820. enumerable: true,
  57821. configurable: true
  57822. });
  57823. /**
  57824. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57825. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57826. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57827. * @returns true if it intersects
  57828. */
  57829. SolidParticle.prototype.intersectsMesh = function (target) {
  57830. if (!this._boundingInfo || !target._boundingInfo) {
  57831. return false;
  57832. }
  57833. if (this._sps._bSphereOnly) {
  57834. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57835. }
  57836. return this._boundingInfo.intersects(target._boundingInfo, false);
  57837. };
  57838. return SolidParticle;
  57839. }());
  57840. BABYLON.SolidParticle = SolidParticle;
  57841. /**
  57842. * Represents the shape of the model used by one particle of a solid particle system.
  57843. * SPS internal tool, don't use it manually.
  57844. */
  57845. var ModelShape = /** @class */ (function () {
  57846. /**
  57847. * 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.
  57848. * SPS internal tool, don't use it manually.
  57849. * @hidden
  57850. */
  57851. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57852. /**
  57853. * length of the shape in the model indices array (internal use)
  57854. */
  57855. this._indicesLength = 0;
  57856. this.shapeID = id;
  57857. this._shape = shape;
  57858. this._indicesLength = indicesLength;
  57859. this._shapeUV = shapeUV;
  57860. this._positionFunction = posFunction;
  57861. this._vertexFunction = vtxFunction;
  57862. }
  57863. return ModelShape;
  57864. }());
  57865. BABYLON.ModelShape = ModelShape;
  57866. /**
  57867. * Represents a Depth Sorted Particle in the solid particle system.
  57868. */
  57869. var DepthSortedParticle = /** @class */ (function () {
  57870. function DepthSortedParticle() {
  57871. /**
  57872. * Index of the particle in the "indices" array
  57873. */
  57874. this.ind = 0;
  57875. /**
  57876. * Length of the particle shape in the "indices" array
  57877. */
  57878. this.indicesLength = 0;
  57879. /**
  57880. * Squared distance from the particle to the camera
  57881. */
  57882. this.sqDistance = 0.0;
  57883. }
  57884. return DepthSortedParticle;
  57885. }());
  57886. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57887. })(BABYLON || (BABYLON = {}));
  57888. //# sourceMappingURL=babylon.solidParticle.js.map
  57889. var BABYLON;
  57890. (function (BABYLON) {
  57891. /**
  57892. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57893. *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.
  57894. * The SPS is also a particle system. It provides some methods to manage the particles.
  57895. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57896. *
  57897. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57898. */
  57899. var SolidParticleSystem = /** @class */ (function () {
  57900. /**
  57901. * Creates a SPS (Solid Particle System) object.
  57902. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57903. * @param scene (Scene) is the scene in which the SPS is added.
  57904. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57905. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57906. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57907. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57908. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57909. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57910. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57911. */
  57912. function SolidParticleSystem(name, scene, options) {
  57913. /**
  57914. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57915. * Example : var p = SPS.particles[i];
  57916. */
  57917. this.particles = new Array();
  57918. /**
  57919. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57920. */
  57921. this.nbParticles = 0;
  57922. /**
  57923. * If the particles must ever face the camera (default false). Useful for planar particles.
  57924. */
  57925. this.billboard = false;
  57926. /**
  57927. * Recompute normals when adding a shape
  57928. */
  57929. this.recomputeNormals = true;
  57930. /**
  57931. * This a counter ofr your own usage. It's not set by any SPS functions.
  57932. */
  57933. this.counter = 0;
  57934. /**
  57935. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57936. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57937. */
  57938. this.vars = {};
  57939. /**
  57940. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57941. */
  57942. this._bSphereOnly = false;
  57943. /**
  57944. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57945. */
  57946. this._bSphereRadiusFactor = 1.0;
  57947. this._positions = new Array();
  57948. this._indices = new Array();
  57949. this._normals = new Array();
  57950. this._colors = new Array();
  57951. this._uvs = new Array();
  57952. this._index = 0; // indices index
  57953. this._updatable = true;
  57954. this._pickable = false;
  57955. this._isVisibilityBoxLocked = false;
  57956. this._alwaysVisible = false;
  57957. this._depthSort = false;
  57958. this._shapeCounter = 0;
  57959. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57960. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57961. this._computeParticleColor = true;
  57962. this._computeParticleTexture = true;
  57963. this._computeParticleRotation = true;
  57964. this._computeParticleVertex = false;
  57965. this._computeBoundingBox = false;
  57966. this._depthSortParticles = true;
  57967. this._cam_axisZ = BABYLON.Vector3.Zero();
  57968. this._cam_axisY = BABYLON.Vector3.Zero();
  57969. this._cam_axisX = BABYLON.Vector3.Zero();
  57970. this._axisZ = BABYLON.Axis.Z;
  57971. this._camDir = BABYLON.Vector3.Zero();
  57972. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57973. this._rotMatrix = new BABYLON.Matrix();
  57974. this._invertMatrix = new BABYLON.Matrix();
  57975. this._rotated = BABYLON.Vector3.Zero();
  57976. this._quaternion = new BABYLON.Quaternion();
  57977. this._vertex = BABYLON.Vector3.Zero();
  57978. this._normal = BABYLON.Vector3.Zero();
  57979. this._yaw = 0.0;
  57980. this._pitch = 0.0;
  57981. this._roll = 0.0;
  57982. this._halfroll = 0.0;
  57983. this._halfpitch = 0.0;
  57984. this._halfyaw = 0.0;
  57985. this._sinRoll = 0.0;
  57986. this._cosRoll = 0.0;
  57987. this._sinPitch = 0.0;
  57988. this._cosPitch = 0.0;
  57989. this._sinYaw = 0.0;
  57990. this._cosYaw = 0.0;
  57991. this._mustUnrotateFixedNormals = false;
  57992. this._minimum = BABYLON.Vector3.Zero();
  57993. this._maximum = BABYLON.Vector3.Zero();
  57994. this._minBbox = BABYLON.Vector3.Zero();
  57995. this._maxBbox = BABYLON.Vector3.Zero();
  57996. this._particlesIntersect = false;
  57997. this._depthSortFunction = function (p1, p2) {
  57998. return (p2.sqDistance - p1.sqDistance);
  57999. };
  58000. this._needs32Bits = false;
  58001. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58002. this._scaledPivot = BABYLON.Vector3.Zero();
  58003. this._particleHasParent = false;
  58004. this.name = name;
  58005. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58006. this._camera = scene.activeCamera;
  58007. this._pickable = options ? options.isPickable : false;
  58008. this._depthSort = options ? options.enableDepthSort : false;
  58009. this._particlesIntersect = options ? options.particleIntersection : false;
  58010. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58011. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58012. if (options && options.updatable !== undefined) {
  58013. this._updatable = options.updatable;
  58014. }
  58015. else {
  58016. this._updatable = true;
  58017. }
  58018. if (this._pickable) {
  58019. this.pickedParticles = [];
  58020. }
  58021. if (this._depthSort) {
  58022. this.depthSortedParticles = [];
  58023. }
  58024. }
  58025. /**
  58026. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58027. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58028. * @returns the created mesh
  58029. */
  58030. SolidParticleSystem.prototype.buildMesh = function () {
  58031. if (this.nbParticles === 0) {
  58032. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58033. this.addShape(triangle, 1);
  58034. triangle.dispose();
  58035. }
  58036. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58037. this._positions32 = new Float32Array(this._positions);
  58038. this._uvs32 = new Float32Array(this._uvs);
  58039. this._colors32 = new Float32Array(this._colors);
  58040. if (this.recomputeNormals) {
  58041. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58042. }
  58043. this._normals32 = new Float32Array(this._normals);
  58044. this._fixedNormal32 = new Float32Array(this._normals);
  58045. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58046. this._unrotateFixedNormals();
  58047. }
  58048. var vertexData = new BABYLON.VertexData();
  58049. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58050. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58051. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58052. if (this._uvs32.length > 0) {
  58053. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58054. }
  58055. if (this._colors32.length > 0) {
  58056. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58057. }
  58058. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58059. vertexData.applyToMesh(mesh, this._updatable);
  58060. this.mesh = mesh;
  58061. this.mesh.isPickable = this._pickable;
  58062. // free memory
  58063. if (!this._depthSort) {
  58064. this._indices = null;
  58065. }
  58066. this._positions = null;
  58067. this._normals = null;
  58068. this._uvs = null;
  58069. this._colors = null;
  58070. if (!this._updatable) {
  58071. this.particles.length = 0;
  58072. }
  58073. return mesh;
  58074. };
  58075. /**
  58076. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58077. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58078. * Thus the particles generated from `digest()` have their property `position` set yet.
  58079. * @param mesh ( Mesh ) is the mesh to be digested
  58080. * @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
  58081. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58082. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58083. * @returns the current SPS
  58084. */
  58085. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58086. var size = (options && options.facetNb) || 1;
  58087. var number = (options && options.number) || 0;
  58088. var delta = (options && options.delta) || 0;
  58089. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58090. var meshInd = mesh.getIndices();
  58091. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58092. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58093. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58094. var f = 0; // facet counter
  58095. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58096. // compute size from number
  58097. if (number) {
  58098. number = (number > totalFacets) ? totalFacets : number;
  58099. size = Math.round(totalFacets / number);
  58100. delta = 0;
  58101. }
  58102. else {
  58103. size = (size > totalFacets) ? totalFacets : size;
  58104. }
  58105. var facetPos = []; // submesh positions
  58106. var facetInd = []; // submesh indices
  58107. var facetUV = []; // submesh UV
  58108. var facetCol = []; // submesh colors
  58109. var barycenter = BABYLON.Vector3.Zero();
  58110. var sizeO = size;
  58111. while (f < totalFacets) {
  58112. size = sizeO + Math.floor((1 + delta) * Math.random());
  58113. if (f > totalFacets - size) {
  58114. size = totalFacets - f;
  58115. }
  58116. // reset temp arrays
  58117. facetPos.length = 0;
  58118. facetInd.length = 0;
  58119. facetUV.length = 0;
  58120. facetCol.length = 0;
  58121. // iterate over "size" facets
  58122. var fi = 0;
  58123. for (var j = f * 3; j < (f + size) * 3; j++) {
  58124. facetInd.push(fi);
  58125. var i = meshInd[j];
  58126. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58127. if (meshUV) {
  58128. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58129. }
  58130. if (meshCol) {
  58131. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58132. }
  58133. fi++;
  58134. }
  58135. // create a model shape for each single particle
  58136. var idx = this.nbParticles;
  58137. var shape = this._posToShape(facetPos);
  58138. var shapeUV = this._uvsToShapeUV(facetUV);
  58139. // compute the barycenter of the shape
  58140. var v;
  58141. for (v = 0; v < shape.length; v++) {
  58142. barycenter.addInPlace(shape[v]);
  58143. }
  58144. barycenter.scaleInPlace(1 / shape.length);
  58145. // shift the shape from its barycenter to the origin
  58146. for (v = 0; v < shape.length; v++) {
  58147. shape[v].subtractInPlace(barycenter);
  58148. }
  58149. var bInfo;
  58150. if (this._particlesIntersect) {
  58151. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58152. }
  58153. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58154. // add the particle in the SPS
  58155. var currentPos = this._positions.length;
  58156. var currentInd = this._indices.length;
  58157. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58158. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58159. // initialize the particle position
  58160. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58161. this._index += shape.length;
  58162. idx++;
  58163. this.nbParticles++;
  58164. this._shapeCounter++;
  58165. f += size;
  58166. }
  58167. return this;
  58168. };
  58169. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58170. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58171. var index = 0;
  58172. var idx = 0;
  58173. for (var p = 0; p < this.particles.length; p++) {
  58174. this._particle = this.particles[p];
  58175. this._shape = this._particle._model._shape;
  58176. if (this._particle.rotationQuaternion) {
  58177. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58178. }
  58179. else {
  58180. this._yaw = this._particle.rotation.y;
  58181. this._pitch = this._particle.rotation.x;
  58182. this._roll = this._particle.rotation.z;
  58183. this._quaternionRotationYPR();
  58184. }
  58185. this._quaternionToRotationMatrix();
  58186. this._rotMatrix.invertToRef(this._invertMatrix);
  58187. for (var pt = 0; pt < this._shape.length; pt++) {
  58188. idx = index + pt * 3;
  58189. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58190. this._fixedNormal32[idx] = this._normal.x;
  58191. this._fixedNormal32[idx + 1] = this._normal.y;
  58192. this._fixedNormal32[idx + 2] = this._normal.z;
  58193. }
  58194. index = idx + 3;
  58195. }
  58196. };
  58197. //reset copy
  58198. SolidParticleSystem.prototype._resetCopy = function () {
  58199. this._copy.position.x = 0;
  58200. this._copy.position.y = 0;
  58201. this._copy.position.z = 0;
  58202. this._copy.rotation.x = 0;
  58203. this._copy.rotation.y = 0;
  58204. this._copy.rotation.z = 0;
  58205. this._copy.rotationQuaternion = null;
  58206. this._copy.scaling.x = 1.0;
  58207. this._copy.scaling.y = 1.0;
  58208. this._copy.scaling.z = 1.0;
  58209. this._copy.uvs.x = 0;
  58210. this._copy.uvs.y = 0;
  58211. this._copy.uvs.z = 1.0;
  58212. this._copy.uvs.w = 1.0;
  58213. this._copy.color = null;
  58214. this._copy.translateFromPivot = false;
  58215. };
  58216. // _meshBuilder : inserts the shape model in the global SPS mesh
  58217. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58218. var i;
  58219. var u = 0;
  58220. var c = 0;
  58221. var n = 0;
  58222. this._resetCopy();
  58223. if (options && options.positionFunction) { // call to custom positionFunction
  58224. options.positionFunction(this._copy, idx, idxInShape);
  58225. this._mustUnrotateFixedNormals = true;
  58226. }
  58227. if (this._copy.rotationQuaternion) {
  58228. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58229. }
  58230. else {
  58231. this._yaw = this._copy.rotation.y;
  58232. this._pitch = this._copy.rotation.x;
  58233. this._roll = this._copy.rotation.z;
  58234. this._quaternionRotationYPR();
  58235. }
  58236. this._quaternionToRotationMatrix();
  58237. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58238. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58239. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58240. if (this._copy.translateFromPivot) {
  58241. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58242. }
  58243. else {
  58244. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58245. }
  58246. for (i = 0; i < shape.length; i++) {
  58247. this._vertex.x = shape[i].x;
  58248. this._vertex.y = shape[i].y;
  58249. this._vertex.z = shape[i].z;
  58250. if (options && options.vertexFunction) {
  58251. options.vertexFunction(this._copy, this._vertex, i);
  58252. }
  58253. this._vertex.x *= this._copy.scaling.x;
  58254. this._vertex.y *= this._copy.scaling.y;
  58255. this._vertex.z *= this._copy.scaling.z;
  58256. this._vertex.x -= this._scaledPivot.x;
  58257. this._vertex.y -= this._scaledPivot.y;
  58258. this._vertex.z -= this._scaledPivot.z;
  58259. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58260. this._rotated.addInPlace(this._pivotBackTranslation);
  58261. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58262. if (meshUV) {
  58263. 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);
  58264. u += 2;
  58265. }
  58266. if (this._copy.color) {
  58267. this._color = this._copy.color;
  58268. }
  58269. else if (meshCol && meshCol[c] !== undefined) {
  58270. this._color.r = meshCol[c];
  58271. this._color.g = meshCol[c + 1];
  58272. this._color.b = meshCol[c + 2];
  58273. this._color.a = meshCol[c + 3];
  58274. }
  58275. else {
  58276. this._color.r = 1.0;
  58277. this._color.g = 1.0;
  58278. this._color.b = 1.0;
  58279. this._color.a = 1.0;
  58280. }
  58281. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58282. c += 4;
  58283. if (!this.recomputeNormals && meshNor) {
  58284. this._normal.x = meshNor[n];
  58285. this._normal.y = meshNor[n + 1];
  58286. this._normal.z = meshNor[n + 2];
  58287. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58288. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58289. n += 3;
  58290. }
  58291. }
  58292. for (i = 0; i < meshInd.length; i++) {
  58293. var current_ind = p + meshInd[i];
  58294. indices.push(current_ind);
  58295. if (current_ind > 65535) {
  58296. this._needs32Bits = true;
  58297. }
  58298. }
  58299. if (this._pickable) {
  58300. var nbfaces = meshInd.length / 3;
  58301. for (i = 0; i < nbfaces; i++) {
  58302. this.pickedParticles.push({ idx: idx, faceId: i });
  58303. }
  58304. }
  58305. if (this._depthSort) {
  58306. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58307. }
  58308. return this._copy;
  58309. };
  58310. // returns a shape array from positions array
  58311. SolidParticleSystem.prototype._posToShape = function (positions) {
  58312. var shape = [];
  58313. for (var i = 0; i < positions.length; i += 3) {
  58314. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58315. }
  58316. return shape;
  58317. };
  58318. // returns a shapeUV array from a Vector4 uvs
  58319. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58320. var shapeUV = [];
  58321. if (uvs) {
  58322. for (var i = 0; i < uvs.length; i++)
  58323. shapeUV.push(uvs[i]);
  58324. }
  58325. return shapeUV;
  58326. };
  58327. // adds a new particle object in the particles array
  58328. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58329. if (bInfo === void 0) { bInfo = null; }
  58330. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58331. this.particles.push(sp);
  58332. return sp;
  58333. };
  58334. /**
  58335. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58336. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58337. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58338. * @param nb (positive integer) the number of particles to be created from this model
  58339. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58340. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58341. * @returns the number of shapes in the system
  58342. */
  58343. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58344. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58345. var meshInd = mesh.getIndices();
  58346. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58347. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58348. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58349. var bbInfo;
  58350. if (this._particlesIntersect) {
  58351. bbInfo = mesh.getBoundingInfo();
  58352. }
  58353. var shape = this._posToShape(meshPos);
  58354. var shapeUV = this._uvsToShapeUV(meshUV);
  58355. var posfunc = options ? options.positionFunction : null;
  58356. var vtxfunc = options ? options.vertexFunction : null;
  58357. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58358. // particles
  58359. var sp;
  58360. var currentCopy;
  58361. var idx = this.nbParticles;
  58362. for (var i = 0; i < nb; i++) {
  58363. var currentPos = this._positions.length;
  58364. var currentInd = this._indices.length;
  58365. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58366. if (this._updatable) {
  58367. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58368. sp.position.copyFrom(currentCopy.position);
  58369. sp.rotation.copyFrom(currentCopy.rotation);
  58370. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58371. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58372. }
  58373. if (currentCopy.color && sp.color) {
  58374. sp.color.copyFrom(currentCopy.color);
  58375. }
  58376. sp.scaling.copyFrom(currentCopy.scaling);
  58377. sp.uvs.copyFrom(currentCopy.uvs);
  58378. }
  58379. this._index += shape.length;
  58380. idx++;
  58381. }
  58382. this.nbParticles += nb;
  58383. this._shapeCounter++;
  58384. return this._shapeCounter - 1;
  58385. };
  58386. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58387. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58388. this._resetCopy();
  58389. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58390. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58391. }
  58392. if (this._copy.rotationQuaternion) {
  58393. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58394. }
  58395. else {
  58396. this._yaw = this._copy.rotation.y;
  58397. this._pitch = this._copy.rotation.x;
  58398. this._roll = this._copy.rotation.z;
  58399. this._quaternionRotationYPR();
  58400. }
  58401. this._quaternionToRotationMatrix();
  58402. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58403. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58404. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58405. if (this._copy.translateFromPivot) {
  58406. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58407. }
  58408. else {
  58409. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58410. }
  58411. this._shape = particle._model._shape;
  58412. for (var pt = 0; pt < this._shape.length; pt++) {
  58413. this._vertex.x = this._shape[pt].x;
  58414. this._vertex.y = this._shape[pt].y;
  58415. this._vertex.z = this._shape[pt].z;
  58416. if (particle._model._vertexFunction) {
  58417. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58418. }
  58419. this._vertex.x *= this._copy.scaling.x;
  58420. this._vertex.y *= this._copy.scaling.y;
  58421. this._vertex.z *= this._copy.scaling.z;
  58422. this._vertex.x -= this._scaledPivot.x;
  58423. this._vertex.y -= this._scaledPivot.y;
  58424. this._vertex.z -= this._scaledPivot.z;
  58425. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58426. this._rotated.addInPlace(this._pivotBackTranslation);
  58427. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58428. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58429. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58430. }
  58431. particle.position.x = 0.0;
  58432. particle.position.y = 0.0;
  58433. particle.position.z = 0.0;
  58434. particle.rotation.x = 0.0;
  58435. particle.rotation.y = 0.0;
  58436. particle.rotation.z = 0.0;
  58437. particle.rotationQuaternion = null;
  58438. particle.scaling.x = 1.0;
  58439. particle.scaling.y = 1.0;
  58440. particle.scaling.z = 1.0;
  58441. particle.uvs.x = 0.0;
  58442. particle.uvs.y = 0.0;
  58443. particle.uvs.z = 1.0;
  58444. particle.uvs.w = 1.0;
  58445. particle.pivot.x = 0.0;
  58446. particle.pivot.y = 0.0;
  58447. particle.pivot.z = 0.0;
  58448. particle.translateFromPivot = false;
  58449. particle.parentId = null;
  58450. };
  58451. /**
  58452. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58453. * @returns the SPS.
  58454. */
  58455. SolidParticleSystem.prototype.rebuildMesh = function () {
  58456. for (var p = 0; p < this.particles.length; p++) {
  58457. this._rebuildParticle(this.particles[p]);
  58458. }
  58459. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58460. return this;
  58461. };
  58462. /**
  58463. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58464. * This method calls `updateParticle()` for each particle of the SPS.
  58465. * For an animated SPS, it is usually called within the render loop.
  58466. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58467. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58468. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58469. * @returns the SPS.
  58470. */
  58471. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58472. if (start === void 0) { start = 0; }
  58473. if (end === void 0) { end = this.nbParticles - 1; }
  58474. if (update === void 0) { update = true; }
  58475. if (!this._updatable) {
  58476. return this;
  58477. }
  58478. // custom beforeUpdate
  58479. this.beforeUpdateParticles(start, end, update);
  58480. this._cam_axisX.x = 1.0;
  58481. this._cam_axisX.y = 0.0;
  58482. this._cam_axisX.z = 0.0;
  58483. this._cam_axisY.x = 0.0;
  58484. this._cam_axisY.y = 1.0;
  58485. this._cam_axisY.z = 0.0;
  58486. this._cam_axisZ.x = 0.0;
  58487. this._cam_axisZ.y = 0.0;
  58488. this._cam_axisZ.z = 1.0;
  58489. // cases when the World Matrix is to be computed first
  58490. if (this.billboard || this._depthSort) {
  58491. this.mesh.computeWorldMatrix(true);
  58492. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58493. }
  58494. // if the particles will always face the camera
  58495. if (this.billboard) {
  58496. // compute the camera position and un-rotate it by the current mesh rotation
  58497. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58498. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58499. this._cam_axisZ.normalize();
  58500. // same for camera up vector extracted from the cam view matrix
  58501. var view = this._camera.getViewMatrix(true);
  58502. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58503. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58504. this._cam_axisY.normalize();
  58505. this._cam_axisX.normalize();
  58506. }
  58507. // if depthSort, compute the camera global position in the mesh local system
  58508. if (this._depthSort) {
  58509. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58510. }
  58511. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58512. var idx = 0; // current position index in the global array positions32
  58513. var index = 0; // position start index in the global array positions32 of the current particle
  58514. var colidx = 0; // current color index in the global array colors32
  58515. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58516. var uvidx = 0; // current uv index in the global array uvs32
  58517. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58518. var pt = 0; // current index in the particle model shape
  58519. if (this.mesh.isFacetDataEnabled) {
  58520. this._computeBoundingBox = true;
  58521. }
  58522. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58523. if (this._computeBoundingBox) {
  58524. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58525. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58526. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58527. }
  58528. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58529. if (this.mesh._boundingInfo) {
  58530. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58531. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58532. }
  58533. }
  58534. }
  58535. // particle loop
  58536. index = this.particles[start]._pos;
  58537. var vpos = (index / 3) | 0;
  58538. colorIndex = vpos * 4;
  58539. uvIndex = vpos * 2;
  58540. for (var p = start; p <= end; p++) {
  58541. this._particle = this.particles[p];
  58542. this._shape = this._particle._model._shape;
  58543. this._shapeUV = this._particle._model._shapeUV;
  58544. // call to custom user function to update the particle properties
  58545. this.updateParticle(this._particle);
  58546. // camera-particle distance for depth sorting
  58547. if (this._depthSort && this._depthSortParticles) {
  58548. var dsp = this.depthSortedParticles[p];
  58549. dsp.ind = this._particle._ind;
  58550. dsp.indicesLength = this._particle._model._indicesLength;
  58551. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58552. }
  58553. // skip the computations for inactive or already invisible particles
  58554. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58555. // increment indexes for the next particle
  58556. pt = this._shape.length;
  58557. index += pt * 3;
  58558. colorIndex += pt * 4;
  58559. uvIndex += pt * 2;
  58560. continue;
  58561. }
  58562. if (this._particle.isVisible) {
  58563. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58564. this._particleHasParent = (this._particle.parentId !== null);
  58565. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58566. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58567. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58568. // particle rotation matrix
  58569. if (this.billboard) {
  58570. this._particle.rotation.x = 0.0;
  58571. this._particle.rotation.y = 0.0;
  58572. }
  58573. if (this._computeParticleRotation || this.billboard) {
  58574. if (this._particle.rotationQuaternion) {
  58575. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58576. }
  58577. else {
  58578. this._yaw = this._particle.rotation.y;
  58579. this._pitch = this._particle.rotation.x;
  58580. this._roll = this._particle.rotation.z;
  58581. this._quaternionRotationYPR();
  58582. }
  58583. this._quaternionToRotationMatrix();
  58584. }
  58585. if (this._particleHasParent) {
  58586. this._parent = this.particles[this._particle.parentId];
  58587. 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];
  58588. 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];
  58589. 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];
  58590. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58591. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58592. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58593. if (this._computeParticleRotation || this.billboard) {
  58594. 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];
  58595. 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];
  58596. 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];
  58597. 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];
  58598. 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];
  58599. 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];
  58600. 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];
  58601. 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];
  58602. 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];
  58603. }
  58604. }
  58605. else {
  58606. this._particle._globalPosition.x = this._particle.position.x;
  58607. this._particle._globalPosition.y = this._particle.position.y;
  58608. this._particle._globalPosition.z = this._particle.position.z;
  58609. if (this._computeParticleRotation || this.billboard) {
  58610. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58611. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58612. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58613. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58614. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58615. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58616. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58617. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58618. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58619. }
  58620. }
  58621. if (this._particle.translateFromPivot) {
  58622. this._pivotBackTranslation.x = 0.0;
  58623. this._pivotBackTranslation.y = 0.0;
  58624. this._pivotBackTranslation.z = 0.0;
  58625. }
  58626. else {
  58627. this._pivotBackTranslation.x = this._scaledPivot.x;
  58628. this._pivotBackTranslation.y = this._scaledPivot.y;
  58629. this._pivotBackTranslation.z = this._scaledPivot.z;
  58630. }
  58631. // particle vertex loop
  58632. for (pt = 0; pt < this._shape.length; pt++) {
  58633. idx = index + pt * 3;
  58634. colidx = colorIndex + pt * 4;
  58635. uvidx = uvIndex + pt * 2;
  58636. this._vertex.x = this._shape[pt].x;
  58637. this._vertex.y = this._shape[pt].y;
  58638. this._vertex.z = this._shape[pt].z;
  58639. if (this._computeParticleVertex) {
  58640. this.updateParticleVertex(this._particle, this._vertex, pt);
  58641. }
  58642. // positions
  58643. this._vertex.x *= this._particle.scaling.x;
  58644. this._vertex.y *= this._particle.scaling.y;
  58645. this._vertex.z *= this._particle.scaling.z;
  58646. this._vertex.x -= this._scaledPivot.x;
  58647. this._vertex.y -= this._scaledPivot.y;
  58648. this._vertex.z -= this._scaledPivot.z;
  58649. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58650. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58651. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58652. this._rotated.x += this._pivotBackTranslation.x;
  58653. this._rotated.y += this._pivotBackTranslation.y;
  58654. this._rotated.z += this._pivotBackTranslation.z;
  58655. 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;
  58656. 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;
  58657. 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;
  58658. if (this._computeBoundingBox) {
  58659. if (this._positions32[idx] < this._minimum.x) {
  58660. this._minimum.x = this._positions32[idx];
  58661. }
  58662. if (this._positions32[idx] > this._maximum.x) {
  58663. this._maximum.x = this._positions32[idx];
  58664. }
  58665. if (this._positions32[idx + 1] < this._minimum.y) {
  58666. this._minimum.y = this._positions32[idx + 1];
  58667. }
  58668. if (this._positions32[idx + 1] > this._maximum.y) {
  58669. this._maximum.y = this._positions32[idx + 1];
  58670. }
  58671. if (this._positions32[idx + 2] < this._minimum.z) {
  58672. this._minimum.z = this._positions32[idx + 2];
  58673. }
  58674. if (this._positions32[idx + 2] > this._maximum.z) {
  58675. this._maximum.z = this._positions32[idx + 2];
  58676. }
  58677. }
  58678. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58679. if (!this._computeParticleVertex) {
  58680. this._normal.x = this._fixedNormal32[idx];
  58681. this._normal.y = this._fixedNormal32[idx + 1];
  58682. this._normal.z = this._fixedNormal32[idx + 2];
  58683. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58684. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58685. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58686. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58687. 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;
  58688. 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;
  58689. }
  58690. if (this._computeParticleColor && this._particle.color) {
  58691. this._colors32[colidx] = this._particle.color.r;
  58692. this._colors32[colidx + 1] = this._particle.color.g;
  58693. this._colors32[colidx + 2] = this._particle.color.b;
  58694. this._colors32[colidx + 3] = this._particle.color.a;
  58695. }
  58696. if (this._computeParticleTexture) {
  58697. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58698. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58699. }
  58700. }
  58701. }
  58702. // particle just set invisible : scaled to zero and positioned at the origin
  58703. else {
  58704. this._particle._stillInvisible = true; // mark the particle as invisible
  58705. for (pt = 0; pt < this._shape.length; pt++) {
  58706. idx = index + pt * 3;
  58707. colidx = colorIndex + pt * 4;
  58708. uvidx = uvIndex + pt * 2;
  58709. this._positions32[idx] = 0.0;
  58710. this._positions32[idx + 1] = 0.0;
  58711. this._positions32[idx + 2] = 0.0;
  58712. this._normals32[idx] = 0.0;
  58713. this._normals32[idx + 1] = 0.0;
  58714. this._normals32[idx + 2] = 0.0;
  58715. if (this._computeParticleColor && this._particle.color) {
  58716. this._colors32[colidx] = this._particle.color.r;
  58717. this._colors32[colidx + 1] = this._particle.color.g;
  58718. this._colors32[colidx + 2] = this._particle.color.b;
  58719. this._colors32[colidx + 3] = this._particle.color.a;
  58720. }
  58721. if (this._computeParticleTexture) {
  58722. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58723. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58724. }
  58725. }
  58726. }
  58727. // if the particle intersections must be computed : update the bbInfo
  58728. if (this._particlesIntersect) {
  58729. var bInfo = this._particle._boundingInfo;
  58730. var bBox = bInfo.boundingBox;
  58731. var bSphere = bInfo.boundingSphere;
  58732. if (!this._bSphereOnly) {
  58733. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58734. for (var b = 0; b < bBox.vectors.length; b++) {
  58735. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58736. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58737. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58738. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58739. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58740. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58741. 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;
  58742. 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;
  58743. 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;
  58744. }
  58745. bBox._update(this.mesh._worldMatrix);
  58746. }
  58747. // place and scale the particle bouding sphere in the SPS local system, then update it
  58748. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58749. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58750. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58751. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58752. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58753. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58754. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58755. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58756. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58757. 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));
  58758. bSphere._update(this.mesh._worldMatrix);
  58759. }
  58760. // increment indexes for the next particle
  58761. index = idx + 3;
  58762. colorIndex = colidx + 4;
  58763. uvIndex = uvidx + 2;
  58764. }
  58765. // if the VBO must be updated
  58766. if (update) {
  58767. if (this._computeParticleColor) {
  58768. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58769. }
  58770. if (this._computeParticleTexture) {
  58771. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58772. }
  58773. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58774. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58775. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58776. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58777. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58778. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58779. for (var i = 0; i < this._normals32.length; i++) {
  58780. this._fixedNormal32[i] = this._normals32[i];
  58781. }
  58782. }
  58783. if (!this.mesh.areNormalsFrozen) {
  58784. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58785. }
  58786. }
  58787. if (this._depthSort && this._depthSortParticles) {
  58788. this.depthSortedParticles.sort(this._depthSortFunction);
  58789. var dspl = this.depthSortedParticles.length;
  58790. var sorted = 0;
  58791. var lind = 0;
  58792. var sind = 0;
  58793. var sid = 0;
  58794. for (sorted = 0; sorted < dspl; sorted++) {
  58795. lind = this.depthSortedParticles[sorted].indicesLength;
  58796. sind = this.depthSortedParticles[sorted].ind;
  58797. for (var i = 0; i < lind; i++) {
  58798. this._indices32[sid] = this._indices[sind + i];
  58799. sid++;
  58800. }
  58801. }
  58802. this.mesh.updateIndices(this._indices32);
  58803. }
  58804. }
  58805. if (this._computeBoundingBox) {
  58806. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58807. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58808. }
  58809. this.afterUpdateParticles(start, end, update);
  58810. return this;
  58811. };
  58812. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58813. this._halfroll = this._roll * 0.5;
  58814. this._halfpitch = this._pitch * 0.5;
  58815. this._halfyaw = this._yaw * 0.5;
  58816. this._sinRoll = Math.sin(this._halfroll);
  58817. this._cosRoll = Math.cos(this._halfroll);
  58818. this._sinPitch = Math.sin(this._halfpitch);
  58819. this._cosPitch = Math.cos(this._halfpitch);
  58820. this._sinYaw = Math.sin(this._halfyaw);
  58821. this._cosYaw = Math.cos(this._halfyaw);
  58822. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58823. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58824. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58825. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58826. };
  58827. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58828. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58829. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58830. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58831. this._rotMatrix.m[3] = 0;
  58832. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58833. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58834. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58835. this._rotMatrix.m[7] = 0;
  58836. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58837. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58838. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58839. this._rotMatrix.m[11] = 0;
  58840. this._rotMatrix.m[12] = 0;
  58841. this._rotMatrix.m[13] = 0;
  58842. this._rotMatrix.m[14] = 0;
  58843. this._rotMatrix.m[15] = 1.0;
  58844. };
  58845. /**
  58846. * Disposes the SPS.
  58847. */
  58848. SolidParticleSystem.prototype.dispose = function () {
  58849. this.mesh.dispose();
  58850. this.vars = null;
  58851. // drop references to internal big arrays for the GC
  58852. this._positions = null;
  58853. this._indices = null;
  58854. this._normals = null;
  58855. this._uvs = null;
  58856. this._colors = null;
  58857. this._indices32 = null;
  58858. this._positions32 = null;
  58859. this._normals32 = null;
  58860. this._fixedNormal32 = null;
  58861. this._uvs32 = null;
  58862. this._colors32 = null;
  58863. this.pickedParticles = null;
  58864. };
  58865. /**
  58866. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58867. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58868. * @returns the SPS.
  58869. */
  58870. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58871. if (!this._isVisibilityBoxLocked) {
  58872. this.mesh.refreshBoundingInfo();
  58873. }
  58874. return this;
  58875. };
  58876. /**
  58877. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58878. * @param size the size (float) of the visibility box
  58879. * note : this doesn't lock the SPS mesh bounding box.
  58880. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58881. */
  58882. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58883. var vis = size / 2;
  58884. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58885. };
  58886. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58887. /**
  58888. * Gets whether the SPS as always visible or not
  58889. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58890. */
  58891. get: function () {
  58892. return this._alwaysVisible;
  58893. },
  58894. /**
  58895. * Sets the SPS as always visible or not
  58896. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58897. */
  58898. set: function (val) {
  58899. this._alwaysVisible = val;
  58900. this.mesh.alwaysSelectAsActiveMesh = val;
  58901. },
  58902. enumerable: true,
  58903. configurable: true
  58904. });
  58905. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58906. /**
  58907. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58908. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58909. */
  58910. get: function () {
  58911. return this._isVisibilityBoxLocked;
  58912. },
  58913. /**
  58914. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58915. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58916. */
  58917. set: function (val) {
  58918. this._isVisibilityBoxLocked = val;
  58919. var boundingInfo = this.mesh.getBoundingInfo();
  58920. boundingInfo.isLocked = val;
  58921. },
  58922. enumerable: true,
  58923. configurable: true
  58924. });
  58925. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58926. /**
  58927. * Gets if `setParticles()` computes the particle rotations or not.
  58928. * Default value : true. The SPS is faster when it's set to false.
  58929. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58930. */
  58931. get: function () {
  58932. return this._computeParticleRotation;
  58933. },
  58934. /**
  58935. * Tells to `setParticles()` to compute the particle rotations or not.
  58936. * Default value : true. The SPS is faster when it's set to false.
  58937. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58938. */
  58939. set: function (val) {
  58940. this._computeParticleRotation = val;
  58941. },
  58942. enumerable: true,
  58943. configurable: true
  58944. });
  58945. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58946. /**
  58947. * Gets if `setParticles()` computes the particle colors or not.
  58948. * Default value : true. The SPS is faster when it's set to false.
  58949. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58950. */
  58951. get: function () {
  58952. return this._computeParticleColor;
  58953. },
  58954. /**
  58955. * Tells to `setParticles()` to compute the particle colors or not.
  58956. * Default value : true. The SPS is faster when it's set to false.
  58957. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58958. */
  58959. set: function (val) {
  58960. this._computeParticleColor = val;
  58961. },
  58962. enumerable: true,
  58963. configurable: true
  58964. });
  58965. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58966. /**
  58967. * Gets if `setParticles()` computes the particle textures or not.
  58968. * Default value : true. The SPS is faster when it's set to false.
  58969. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58970. */
  58971. get: function () {
  58972. return this._computeParticleTexture;
  58973. },
  58974. set: function (val) {
  58975. this._computeParticleTexture = val;
  58976. },
  58977. enumerable: true,
  58978. configurable: true
  58979. });
  58980. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58981. /**
  58982. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58983. * Default value : false. The SPS is faster when it's set to false.
  58984. * Note : the particle custom vertex positions aren't stored values.
  58985. */
  58986. get: function () {
  58987. return this._computeParticleVertex;
  58988. },
  58989. /**
  58990. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58991. * Default value : false. The SPS is faster when it's set to false.
  58992. * Note : the particle custom vertex positions aren't stored values.
  58993. */
  58994. set: function (val) {
  58995. this._computeParticleVertex = val;
  58996. },
  58997. enumerable: true,
  58998. configurable: true
  58999. });
  59000. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59001. /**
  59002. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59003. */
  59004. get: function () {
  59005. return this._computeBoundingBox;
  59006. },
  59007. /**
  59008. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59009. */
  59010. set: function (val) {
  59011. this._computeBoundingBox = val;
  59012. },
  59013. enumerable: true,
  59014. configurable: true
  59015. });
  59016. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59017. /**
  59018. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59019. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59020. * Default : `true`
  59021. */
  59022. get: function () {
  59023. return this._depthSortParticles;
  59024. },
  59025. /**
  59026. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59027. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59028. * Default : `true`
  59029. */
  59030. set: function (val) {
  59031. this._depthSortParticles = val;
  59032. },
  59033. enumerable: true,
  59034. configurable: true
  59035. });
  59036. // =======================================================================
  59037. // Particle behavior logic
  59038. // these following methods may be overwritten by the user to fit his needs
  59039. /**
  59040. * This function does nothing. It may be overwritten to set all the particle first values.
  59041. * The SPS doesn't call this function, you may have to call it by your own.
  59042. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59043. */
  59044. SolidParticleSystem.prototype.initParticles = function () {
  59045. };
  59046. /**
  59047. * This function does nothing. It may be overwritten to recycle a particle.
  59048. * The SPS doesn't call this function, you may have to call it by your own.
  59049. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59050. * @param particle The particle to recycle
  59051. * @returns the recycled particle
  59052. */
  59053. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59054. return particle;
  59055. };
  59056. /**
  59057. * Updates a particle : this function should be overwritten by the user.
  59058. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59059. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59060. * @example : just set a particle position or velocity and recycle conditions
  59061. * @param particle The particle to update
  59062. * @returns the updated particle
  59063. */
  59064. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59065. return particle;
  59066. };
  59067. /**
  59068. * Updates a vertex of a particle : it can be overwritten by the user.
  59069. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59070. * @param particle the current particle
  59071. * @param vertex the current index of the current particle
  59072. * @param pt the index of the current vertex in the particle shape
  59073. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59074. * @example : just set a vertex particle position
  59075. * @returns the updated vertex
  59076. */
  59077. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59078. return vertex;
  59079. };
  59080. /**
  59081. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59082. * This does nothing and may be overwritten by the user.
  59083. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59084. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59085. * @param update the boolean update value actually passed to setParticles()
  59086. */
  59087. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59088. };
  59089. /**
  59090. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59091. * This will be passed three parameters.
  59092. * This does nothing and may be overwritten by the user.
  59093. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59094. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59095. * @param update the boolean update value actually passed to setParticles()
  59096. */
  59097. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59098. };
  59099. return SolidParticleSystem;
  59100. }());
  59101. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59102. })(BABYLON || (BABYLON = {}));
  59103. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59104. var BABYLON;
  59105. (function (BABYLON) {
  59106. var ShaderMaterial = /** @class */ (function (_super) {
  59107. __extends(ShaderMaterial, _super);
  59108. function ShaderMaterial(name, scene, shaderPath, options) {
  59109. var _this = _super.call(this, name, scene) || this;
  59110. _this._textures = {};
  59111. _this._textureArrays = {};
  59112. _this._floats = {};
  59113. _this._ints = {};
  59114. _this._floatsArrays = {};
  59115. _this._colors3 = {};
  59116. _this._colors3Arrays = {};
  59117. _this._colors4 = {};
  59118. _this._vectors2 = {};
  59119. _this._vectors3 = {};
  59120. _this._vectors4 = {};
  59121. _this._matrices = {};
  59122. _this._matrices3x3 = {};
  59123. _this._matrices2x2 = {};
  59124. _this._vectors2Arrays = {};
  59125. _this._vectors3Arrays = {};
  59126. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59127. _this._shaderPath = shaderPath;
  59128. options.needAlphaBlending = options.needAlphaBlending || false;
  59129. options.needAlphaTesting = options.needAlphaTesting || false;
  59130. options.attributes = options.attributes || ["position", "normal", "uv"];
  59131. options.uniforms = options.uniforms || ["worldViewProjection"];
  59132. options.uniformBuffers = options.uniformBuffers || [];
  59133. options.samplers = options.samplers || [];
  59134. options.defines = options.defines || [];
  59135. _this._options = options;
  59136. return _this;
  59137. }
  59138. ShaderMaterial.prototype.getClassName = function () {
  59139. return "ShaderMaterial";
  59140. };
  59141. ShaderMaterial.prototype.needAlphaBlending = function () {
  59142. return this._options.needAlphaBlending;
  59143. };
  59144. ShaderMaterial.prototype.needAlphaTesting = function () {
  59145. return this._options.needAlphaTesting;
  59146. };
  59147. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59148. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59149. this._options.uniforms.push(uniformName);
  59150. }
  59151. };
  59152. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59153. if (this._options.samplers.indexOf(name) === -1) {
  59154. this._options.samplers.push(name);
  59155. }
  59156. this._textures[name] = texture;
  59157. return this;
  59158. };
  59159. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59160. if (this._options.samplers.indexOf(name) === -1) {
  59161. this._options.samplers.push(name);
  59162. }
  59163. this._checkUniform(name);
  59164. this._textureArrays[name] = textures;
  59165. return this;
  59166. };
  59167. ShaderMaterial.prototype.setFloat = function (name, value) {
  59168. this._checkUniform(name);
  59169. this._floats[name] = value;
  59170. return this;
  59171. };
  59172. ShaderMaterial.prototype.setInt = function (name, value) {
  59173. this._checkUniform(name);
  59174. this._ints[name] = value;
  59175. return this;
  59176. };
  59177. ShaderMaterial.prototype.setFloats = function (name, value) {
  59178. this._checkUniform(name);
  59179. this._floatsArrays[name] = value;
  59180. return this;
  59181. };
  59182. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59183. this._checkUniform(name);
  59184. this._colors3[name] = value;
  59185. return this;
  59186. };
  59187. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59188. this._checkUniform(name);
  59189. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59190. color.toArray(arr, arr.length);
  59191. return arr;
  59192. }, []);
  59193. return this;
  59194. };
  59195. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59196. this._checkUniform(name);
  59197. this._colors4[name] = value;
  59198. return this;
  59199. };
  59200. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59201. this._checkUniform(name);
  59202. this._vectors2[name] = value;
  59203. return this;
  59204. };
  59205. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59206. this._checkUniform(name);
  59207. this._vectors3[name] = value;
  59208. return this;
  59209. };
  59210. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59211. this._checkUniform(name);
  59212. this._vectors4[name] = value;
  59213. return this;
  59214. };
  59215. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59216. this._checkUniform(name);
  59217. this._matrices[name] = value;
  59218. return this;
  59219. };
  59220. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59221. this._checkUniform(name);
  59222. this._matrices3x3[name] = value;
  59223. return this;
  59224. };
  59225. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59226. this._checkUniform(name);
  59227. this._matrices2x2[name] = value;
  59228. return this;
  59229. };
  59230. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59231. this._checkUniform(name);
  59232. this._vectors2Arrays[name] = value;
  59233. return this;
  59234. };
  59235. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59236. this._checkUniform(name);
  59237. this._vectors3Arrays[name] = value;
  59238. return this;
  59239. };
  59240. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59241. if (!mesh) {
  59242. return true;
  59243. }
  59244. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59245. return false;
  59246. }
  59247. return false;
  59248. };
  59249. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59250. var scene = this.getScene();
  59251. var engine = scene.getEngine();
  59252. if (!this.checkReadyOnEveryCall) {
  59253. if (this._renderId === scene.getRenderId()) {
  59254. if (this._checkCache(scene, mesh, useInstances)) {
  59255. return true;
  59256. }
  59257. }
  59258. }
  59259. // Instances
  59260. var defines = [];
  59261. var attribs = [];
  59262. var fallbacks = new BABYLON.EffectFallbacks();
  59263. if (useInstances) {
  59264. defines.push("#define INSTANCES");
  59265. }
  59266. for (var index = 0; index < this._options.defines.length; index++) {
  59267. defines.push(this._options.defines[index]);
  59268. }
  59269. for (var index = 0; index < this._options.attributes.length; index++) {
  59270. attribs.push(this._options.attributes[index]);
  59271. }
  59272. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59273. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59274. defines.push("#define VERTEXCOLOR");
  59275. }
  59276. // Bones
  59277. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59278. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59279. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59280. if (mesh.numBoneInfluencers > 4) {
  59281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59283. }
  59284. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59285. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59286. fallbacks.addCPUSkinningFallback(0, mesh);
  59287. if (this._options.uniforms.indexOf("mBones") === -1) {
  59288. this._options.uniforms.push("mBones");
  59289. }
  59290. }
  59291. else {
  59292. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59293. }
  59294. // Textures
  59295. for (var name in this._textures) {
  59296. if (!this._textures[name].isReady()) {
  59297. return false;
  59298. }
  59299. }
  59300. // Alpha test
  59301. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59302. defines.push("#define ALPHATEST");
  59303. }
  59304. var previousEffect = this._effect;
  59305. var join = defines.join("\n");
  59306. this._effect = engine.createEffect(this._shaderPath, {
  59307. attributes: attribs,
  59308. uniformsNames: this._options.uniforms,
  59309. uniformBuffersNames: this._options.uniformBuffers,
  59310. samplers: this._options.samplers,
  59311. defines: join,
  59312. fallbacks: fallbacks,
  59313. onCompiled: this.onCompiled,
  59314. onError: this.onError
  59315. }, engine);
  59316. if (!this._effect.isReady()) {
  59317. return false;
  59318. }
  59319. if (previousEffect !== this._effect) {
  59320. scene.resetCachedMaterial();
  59321. }
  59322. this._renderId = scene.getRenderId();
  59323. return true;
  59324. };
  59325. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59326. var scene = this.getScene();
  59327. if (!this._effect) {
  59328. return;
  59329. }
  59330. if (this._options.uniforms.indexOf("world") !== -1) {
  59331. this._effect.setMatrix("world", world);
  59332. }
  59333. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59334. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59335. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59336. }
  59337. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59338. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59339. }
  59340. };
  59341. ShaderMaterial.prototype.bind = function (world, mesh) {
  59342. // Std values
  59343. this.bindOnlyWorldMatrix(world);
  59344. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59345. if (this._options.uniforms.indexOf("view") !== -1) {
  59346. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59347. }
  59348. if (this._options.uniforms.indexOf("projection") !== -1) {
  59349. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59350. }
  59351. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59352. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59353. }
  59354. // Bones
  59355. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59356. var name;
  59357. // Texture
  59358. for (name in this._textures) {
  59359. this._effect.setTexture(name, this._textures[name]);
  59360. }
  59361. // Texture arrays
  59362. for (name in this._textureArrays) {
  59363. this._effect.setTextureArray(name, this._textureArrays[name]);
  59364. }
  59365. // Int
  59366. for (name in this._ints) {
  59367. this._effect.setInt(name, this._ints[name]);
  59368. }
  59369. // Float
  59370. for (name in this._floats) {
  59371. this._effect.setFloat(name, this._floats[name]);
  59372. }
  59373. // Floats
  59374. for (name in this._floatsArrays) {
  59375. this._effect.setArray(name, this._floatsArrays[name]);
  59376. }
  59377. // Color3
  59378. for (name in this._colors3) {
  59379. this._effect.setColor3(name, this._colors3[name]);
  59380. }
  59381. for (name in this._colors3Arrays) {
  59382. this._effect.setArray3(name, this._colors3Arrays[name]);
  59383. }
  59384. // Color4
  59385. for (name in this._colors4) {
  59386. var color = this._colors4[name];
  59387. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59388. }
  59389. // Vector2
  59390. for (name in this._vectors2) {
  59391. this._effect.setVector2(name, this._vectors2[name]);
  59392. }
  59393. // Vector3
  59394. for (name in this._vectors3) {
  59395. this._effect.setVector3(name, this._vectors3[name]);
  59396. }
  59397. // Vector4
  59398. for (name in this._vectors4) {
  59399. this._effect.setVector4(name, this._vectors4[name]);
  59400. }
  59401. // Matrix
  59402. for (name in this._matrices) {
  59403. this._effect.setMatrix(name, this._matrices[name]);
  59404. }
  59405. // Matrix 3x3
  59406. for (name in this._matrices3x3) {
  59407. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59408. }
  59409. // Matrix 2x2
  59410. for (name in this._matrices2x2) {
  59411. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59412. }
  59413. // Vector2Array
  59414. for (name in this._vectors2Arrays) {
  59415. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59416. }
  59417. // Vector3Array
  59418. for (name in this._vectors3Arrays) {
  59419. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59420. }
  59421. }
  59422. this._afterBind(mesh);
  59423. };
  59424. ShaderMaterial.prototype.getActiveTextures = function () {
  59425. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59426. for (var name in this._textures) {
  59427. activeTextures.push(this._textures[name]);
  59428. }
  59429. for (var name in this._textureArrays) {
  59430. var array = this._textureArrays[name];
  59431. for (var index = 0; index < array.length; index++) {
  59432. activeTextures.push(array[index]);
  59433. }
  59434. }
  59435. return activeTextures;
  59436. };
  59437. ShaderMaterial.prototype.hasTexture = function (texture) {
  59438. if (_super.prototype.hasTexture.call(this, texture)) {
  59439. return true;
  59440. }
  59441. for (var name in this._textures) {
  59442. if (this._textures[name] === texture) {
  59443. return true;
  59444. }
  59445. }
  59446. for (var name in this._textureArrays) {
  59447. var array = this._textureArrays[name];
  59448. for (var index = 0; index < array.length; index++) {
  59449. if (array[index] === texture) {
  59450. return true;
  59451. }
  59452. }
  59453. }
  59454. return false;
  59455. };
  59456. ShaderMaterial.prototype.clone = function (name) {
  59457. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59458. return newShaderMaterial;
  59459. };
  59460. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59461. if (forceDisposeTextures) {
  59462. var name;
  59463. for (name in this._textures) {
  59464. this._textures[name].dispose();
  59465. }
  59466. for (name in this._textureArrays) {
  59467. var array = this._textureArrays[name];
  59468. for (var index = 0; index < array.length; index++) {
  59469. array[index].dispose();
  59470. }
  59471. }
  59472. }
  59473. this._textures = {};
  59474. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59475. };
  59476. ShaderMaterial.prototype.serialize = function () {
  59477. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59478. serializationObject.customType = "BABYLON.ShaderMaterial";
  59479. serializationObject.options = this._options;
  59480. serializationObject.shaderPath = this._shaderPath;
  59481. var name;
  59482. // Texture
  59483. serializationObject.textures = {};
  59484. for (name in this._textures) {
  59485. serializationObject.textures[name] = this._textures[name].serialize();
  59486. }
  59487. // Texture arrays
  59488. serializationObject.textureArrays = {};
  59489. for (name in this._textureArrays) {
  59490. serializationObject.textureArrays[name] = [];
  59491. var array = this._textureArrays[name];
  59492. for (var index = 0; index < array.length; index++) {
  59493. serializationObject.textureArrays[name].push(array[index].serialize());
  59494. }
  59495. }
  59496. // Float
  59497. serializationObject.floats = {};
  59498. for (name in this._floats) {
  59499. serializationObject.floats[name] = this._floats[name];
  59500. }
  59501. // Float s
  59502. serializationObject.FloatArrays = {};
  59503. for (name in this._floatsArrays) {
  59504. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59505. }
  59506. // Color3
  59507. serializationObject.colors3 = {};
  59508. for (name in this._colors3) {
  59509. serializationObject.colors3[name] = this._colors3[name].asArray();
  59510. }
  59511. // Color3 array
  59512. serializationObject.colors3Arrays = {};
  59513. for (name in this._colors3Arrays) {
  59514. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59515. }
  59516. // Color4
  59517. serializationObject.colors4 = {};
  59518. for (name in this._colors4) {
  59519. serializationObject.colors4[name] = this._colors4[name].asArray();
  59520. }
  59521. // Vector2
  59522. serializationObject.vectors2 = {};
  59523. for (name in this._vectors2) {
  59524. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59525. }
  59526. // Vector3
  59527. serializationObject.vectors3 = {};
  59528. for (name in this._vectors3) {
  59529. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59530. }
  59531. // Vector4
  59532. serializationObject.vectors4 = {};
  59533. for (name in this._vectors4) {
  59534. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59535. }
  59536. // Matrix
  59537. serializationObject.matrices = {};
  59538. for (name in this._matrices) {
  59539. serializationObject.matrices[name] = this._matrices[name].asArray();
  59540. }
  59541. // Matrix 3x3
  59542. serializationObject.matrices3x3 = {};
  59543. for (name in this._matrices3x3) {
  59544. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59545. }
  59546. // Matrix 2x2
  59547. serializationObject.matrices2x2 = {};
  59548. for (name in this._matrices2x2) {
  59549. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59550. }
  59551. // Vector2Array
  59552. serializationObject.vectors2Arrays = {};
  59553. for (name in this._vectors2Arrays) {
  59554. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59555. }
  59556. // Vector3Array
  59557. serializationObject.vectors3Arrays = {};
  59558. for (name in this._vectors3Arrays) {
  59559. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59560. }
  59561. return serializationObject;
  59562. };
  59563. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59564. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59565. var name;
  59566. // Texture
  59567. for (name in source.textures) {
  59568. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59569. }
  59570. // Texture arrays
  59571. for (name in source.textureArrays) {
  59572. var array = source.textureArrays[name];
  59573. var textureArray = new Array();
  59574. for (var index = 0; index < array.length; index++) {
  59575. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59576. }
  59577. material.setTextureArray(name, textureArray);
  59578. }
  59579. // Float
  59580. for (name in source.floats) {
  59581. material.setFloat(name, source.floats[name]);
  59582. }
  59583. // Float s
  59584. for (name in source.floatsArrays) {
  59585. material.setFloats(name, source.floatsArrays[name]);
  59586. }
  59587. // Color3
  59588. for (name in source.colors3) {
  59589. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59590. }
  59591. // Color3 arrays
  59592. for (name in source.colors3Arrays) {
  59593. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59594. if (i % 3 === 0) {
  59595. arr.push([num]);
  59596. }
  59597. else {
  59598. arr[arr.length - 1].push(num);
  59599. }
  59600. return arr;
  59601. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59602. material.setColor3Array(name, colors);
  59603. }
  59604. // Color4
  59605. for (name in source.colors4) {
  59606. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59607. }
  59608. // Vector2
  59609. for (name in source.vectors2) {
  59610. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59611. }
  59612. // Vector3
  59613. for (name in source.vectors3) {
  59614. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59615. }
  59616. // Vector4
  59617. for (name in source.vectors4) {
  59618. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59619. }
  59620. // Matrix
  59621. for (name in source.matrices) {
  59622. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59623. }
  59624. // Matrix 3x3
  59625. for (name in source.matrices3x3) {
  59626. material.setMatrix3x3(name, source.matrices3x3[name]);
  59627. }
  59628. // Matrix 2x2
  59629. for (name in source.matrices2x2) {
  59630. material.setMatrix2x2(name, source.matrices2x2[name]);
  59631. }
  59632. // Vector2Array
  59633. for (name in source.vectors2Arrays) {
  59634. material.setArray2(name, source.vectors2Arrays[name]);
  59635. }
  59636. // Vector3Array
  59637. for (name in source.vectors3Arrays) {
  59638. material.setArray3(name, source.vectors3Arrays[name]);
  59639. }
  59640. return material;
  59641. };
  59642. return ShaderMaterial;
  59643. }(BABYLON.Material));
  59644. BABYLON.ShaderMaterial = ShaderMaterial;
  59645. })(BABYLON || (BABYLON = {}));
  59646. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59647. var BABYLON;
  59648. (function (BABYLON) {
  59649. var GroundMesh = /** @class */ (function (_super) {
  59650. __extends(GroundMesh, _super);
  59651. function GroundMesh(name, scene) {
  59652. var _this = _super.call(this, name, scene) || this;
  59653. _this.generateOctree = false;
  59654. return _this;
  59655. }
  59656. GroundMesh.prototype.getClassName = function () {
  59657. return "GroundMesh";
  59658. };
  59659. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59660. get: function () {
  59661. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59662. },
  59663. enumerable: true,
  59664. configurable: true
  59665. });
  59666. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59667. get: function () {
  59668. return this._subdivisionsX;
  59669. },
  59670. enumerable: true,
  59671. configurable: true
  59672. });
  59673. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59674. get: function () {
  59675. return this._subdivisionsY;
  59676. },
  59677. enumerable: true,
  59678. configurable: true
  59679. });
  59680. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59681. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59682. this._subdivisionsX = chunksCount;
  59683. this._subdivisionsY = chunksCount;
  59684. this.subdivide(chunksCount);
  59685. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59686. };
  59687. /**
  59688. * Returns a height (y) value in the Worl system :
  59689. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59690. * Returns the ground y position if (x, z) are outside the ground surface.
  59691. */
  59692. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59693. var world = this.getWorldMatrix();
  59694. var invMat = BABYLON.Tmp.Matrix[5];
  59695. world.invertToRef(invMat);
  59696. var tmpVect = BABYLON.Tmp.Vector3[8];
  59697. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59698. x = tmpVect.x;
  59699. z = tmpVect.z;
  59700. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59701. return this.position.y;
  59702. }
  59703. if (!this._heightQuads || this._heightQuads.length == 0) {
  59704. this._initHeightQuads();
  59705. this._computeHeightQuads();
  59706. }
  59707. var facet = this._getFacetAt(x, z);
  59708. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59709. // return y in the World system
  59710. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59711. return tmpVect.y;
  59712. };
  59713. /**
  59714. * Returns a normalized vector (Vector3) orthogonal to the ground
  59715. * at the ground coordinates (x, z) expressed in the World system.
  59716. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59717. */
  59718. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59719. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59720. this.getNormalAtCoordinatesToRef(x, z, normal);
  59721. return normal;
  59722. };
  59723. /**
  59724. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59725. * at the ground coordinates (x, z) expressed in the World system.
  59726. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59727. * Returns the GroundMesh.
  59728. */
  59729. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59730. var world = this.getWorldMatrix();
  59731. var tmpMat = BABYLON.Tmp.Matrix[5];
  59732. world.invertToRef(tmpMat);
  59733. var tmpVect = BABYLON.Tmp.Vector3[8];
  59734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59735. x = tmpVect.x;
  59736. z = tmpVect.z;
  59737. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59738. return this;
  59739. }
  59740. if (!this._heightQuads || this._heightQuads.length == 0) {
  59741. this._initHeightQuads();
  59742. this._computeHeightQuads();
  59743. }
  59744. var facet = this._getFacetAt(x, z);
  59745. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59746. return this;
  59747. };
  59748. /**
  59749. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59750. * if the ground has been updated.
  59751. * This can be used in the render loop.
  59752. * Returns the GroundMesh.
  59753. */
  59754. GroundMesh.prototype.updateCoordinateHeights = function () {
  59755. if (!this._heightQuads || this._heightQuads.length == 0) {
  59756. this._initHeightQuads();
  59757. }
  59758. this._computeHeightQuads();
  59759. return this;
  59760. };
  59761. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59762. GroundMesh.prototype._getFacetAt = function (x, z) {
  59763. // retrieve col and row from x, z coordinates in the ground local system
  59764. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59765. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59766. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59767. var facet;
  59768. if (z < quad.slope.x * x + quad.slope.y) {
  59769. facet = quad.facet1;
  59770. }
  59771. else {
  59772. facet = quad.facet2;
  59773. }
  59774. return facet;
  59775. };
  59776. // Creates and populates the heightMap array with "facet" elements :
  59777. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59778. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59779. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59780. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59781. // Returns the GroundMesh.
  59782. GroundMesh.prototype._initHeightQuads = function () {
  59783. var subdivisionsX = this._subdivisionsX;
  59784. var subdivisionsY = this._subdivisionsY;
  59785. this._heightQuads = new Array();
  59786. for (var row = 0; row < subdivisionsY; row++) {
  59787. for (var col = 0; col < subdivisionsX; col++) {
  59788. 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) };
  59789. this._heightQuads[row * subdivisionsX + col] = quad;
  59790. }
  59791. }
  59792. return this;
  59793. };
  59794. // Compute each quad element values and update the the heightMap array :
  59795. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59796. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59797. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59798. // Returns the GroundMesh.
  59799. GroundMesh.prototype._computeHeightQuads = function () {
  59800. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59801. if (!positions) {
  59802. return this;
  59803. }
  59804. var v1 = BABYLON.Tmp.Vector3[3];
  59805. var v2 = BABYLON.Tmp.Vector3[2];
  59806. var v3 = BABYLON.Tmp.Vector3[1];
  59807. var v4 = BABYLON.Tmp.Vector3[0];
  59808. var v1v2 = BABYLON.Tmp.Vector3[4];
  59809. var v1v3 = BABYLON.Tmp.Vector3[5];
  59810. var v1v4 = BABYLON.Tmp.Vector3[6];
  59811. var norm1 = BABYLON.Tmp.Vector3[7];
  59812. var norm2 = BABYLON.Tmp.Vector3[8];
  59813. var i = 0;
  59814. var j = 0;
  59815. var k = 0;
  59816. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59817. var h = 0;
  59818. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59819. var d2 = 0;
  59820. var subdivisionsX = this._subdivisionsX;
  59821. var subdivisionsY = this._subdivisionsY;
  59822. for (var row = 0; row < subdivisionsY; row++) {
  59823. for (var col = 0; col < subdivisionsX; col++) {
  59824. i = col * 3;
  59825. j = row * (subdivisionsX + 1) * 3;
  59826. k = (row + 1) * (subdivisionsX + 1) * 3;
  59827. v1.x = positions[j + i];
  59828. v1.y = positions[j + i + 1];
  59829. v1.z = positions[j + i + 2];
  59830. v2.x = positions[j + i + 3];
  59831. v2.y = positions[j + i + 4];
  59832. v2.z = positions[j + i + 5];
  59833. v3.x = positions[k + i];
  59834. v3.y = positions[k + i + 1];
  59835. v3.z = positions[k + i + 2];
  59836. v4.x = positions[k + i + 3];
  59837. v4.y = positions[k + i + 4];
  59838. v4.z = positions[k + i + 5];
  59839. // 2D slope V1V4
  59840. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59841. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59842. // facet equations :
  59843. // we compute each facet normal vector
  59844. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59845. // we compute the value d by applying the equation to v1 which belongs to the plane
  59846. // then we store the facet equation in a Vector4
  59847. v2.subtractToRef(v1, v1v2);
  59848. v3.subtractToRef(v1, v1v3);
  59849. v4.subtractToRef(v1, v1v4);
  59850. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59851. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59852. norm1.normalize();
  59853. norm2.normalize();
  59854. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59855. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59856. var quad = this._heightQuads[row * subdivisionsX + col];
  59857. quad.slope.copyFromFloats(cd, h);
  59858. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59859. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59860. }
  59861. }
  59862. return this;
  59863. };
  59864. GroundMesh.prototype.serialize = function (serializationObject) {
  59865. _super.prototype.serialize.call(this, serializationObject);
  59866. serializationObject.subdivisionsX = this._subdivisionsX;
  59867. serializationObject.subdivisionsY = this._subdivisionsY;
  59868. serializationObject.minX = this._minX;
  59869. serializationObject.maxX = this._maxX;
  59870. serializationObject.minZ = this._minZ;
  59871. serializationObject.maxZ = this._maxZ;
  59872. serializationObject.width = this._width;
  59873. serializationObject.height = this._height;
  59874. };
  59875. GroundMesh.Parse = function (parsedMesh, scene) {
  59876. var result = new GroundMesh(parsedMesh.name, scene);
  59877. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59878. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59879. result._minX = parsedMesh.minX;
  59880. result._maxX = parsedMesh.maxX;
  59881. result._minZ = parsedMesh.minZ;
  59882. result._maxZ = parsedMesh.maxZ;
  59883. result._width = parsedMesh.width;
  59884. result._height = parsedMesh.height;
  59885. return result;
  59886. };
  59887. return GroundMesh;
  59888. }(BABYLON.Mesh));
  59889. BABYLON.GroundMesh = GroundMesh;
  59890. })(BABYLON || (BABYLON = {}));
  59891. //# sourceMappingURL=babylon.groundMesh.js.map
  59892. var BABYLON;
  59893. (function (BABYLON) {
  59894. /**
  59895. * Creates an instance based on a source mesh.
  59896. */
  59897. var InstancedMesh = /** @class */ (function (_super) {
  59898. __extends(InstancedMesh, _super);
  59899. function InstancedMesh(name, source) {
  59900. var _this = _super.call(this, name, source.getScene()) || this;
  59901. source.instances.push(_this);
  59902. _this._sourceMesh = source;
  59903. _this.position.copyFrom(source.position);
  59904. _this.rotation.copyFrom(source.rotation);
  59905. _this.scaling.copyFrom(source.scaling);
  59906. if (source.rotationQuaternion) {
  59907. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59908. }
  59909. _this.infiniteDistance = source.infiniteDistance;
  59910. _this.setPivotMatrix(source.getPivotMatrix());
  59911. _this.refreshBoundingInfo();
  59912. _this._syncSubMeshes();
  59913. return _this;
  59914. }
  59915. /**
  59916. * Returns the string "InstancedMesh".
  59917. */
  59918. InstancedMesh.prototype.getClassName = function () {
  59919. return "InstancedMesh";
  59920. };
  59921. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59922. // Methods
  59923. get: function () {
  59924. return this._sourceMesh.receiveShadows;
  59925. },
  59926. enumerable: true,
  59927. configurable: true
  59928. });
  59929. Object.defineProperty(InstancedMesh.prototype, "material", {
  59930. get: function () {
  59931. return this._sourceMesh.material;
  59932. },
  59933. enumerable: true,
  59934. configurable: true
  59935. });
  59936. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59937. get: function () {
  59938. return this._sourceMesh.visibility;
  59939. },
  59940. enumerable: true,
  59941. configurable: true
  59942. });
  59943. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59944. get: function () {
  59945. return this._sourceMesh.skeleton;
  59946. },
  59947. enumerable: true,
  59948. configurable: true
  59949. });
  59950. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59951. get: function () {
  59952. return this._sourceMesh.renderingGroupId;
  59953. },
  59954. set: function (value) {
  59955. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59956. return;
  59957. }
  59958. //no-op with warning
  59959. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59960. },
  59961. enumerable: true,
  59962. configurable: true
  59963. });
  59964. /**
  59965. * Returns the total number of vertices (integer).
  59966. */
  59967. InstancedMesh.prototype.getTotalVertices = function () {
  59968. return this._sourceMesh.getTotalVertices();
  59969. };
  59970. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59971. get: function () {
  59972. return this._sourceMesh;
  59973. },
  59974. enumerable: true,
  59975. configurable: true
  59976. });
  59977. /**
  59978. * Is this node ready to be used/rendered
  59979. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59980. * @return {boolean} is it ready
  59981. */
  59982. InstancedMesh.prototype.isReady = function (completeCheck) {
  59983. if (completeCheck === void 0) { completeCheck = false; }
  59984. return this._sourceMesh.isReady(completeCheck, true);
  59985. };
  59986. /**
  59987. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59988. */
  59989. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59990. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59991. };
  59992. /**
  59993. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59994. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59995. * The `data` are either a numeric array either a Float32Array.
  59996. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59997. * 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).
  59998. * Note that a new underlying VertexBuffer object is created each call.
  59999. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60000. *
  60001. * Possible `kind` values :
  60002. * - BABYLON.VertexBuffer.PositionKind
  60003. * - BABYLON.VertexBuffer.UVKind
  60004. * - BABYLON.VertexBuffer.UV2Kind
  60005. * - BABYLON.VertexBuffer.UV3Kind
  60006. * - BABYLON.VertexBuffer.UV4Kind
  60007. * - BABYLON.VertexBuffer.UV5Kind
  60008. * - BABYLON.VertexBuffer.UV6Kind
  60009. * - BABYLON.VertexBuffer.ColorKind
  60010. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60011. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60012. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60013. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60014. *
  60015. * Returns the Mesh.
  60016. */
  60017. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60018. if (this.sourceMesh) {
  60019. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60020. }
  60021. return this.sourceMesh;
  60022. };
  60023. /**
  60024. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60025. * If the mesh has no geometry, it is simply returned as it is.
  60026. * The `data` are either a numeric array either a Float32Array.
  60027. * No new underlying VertexBuffer object is created.
  60028. * 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.
  60029. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60030. *
  60031. * Possible `kind` values :
  60032. * - BABYLON.VertexBuffer.PositionKind
  60033. * - BABYLON.VertexBuffer.UVKind
  60034. * - BABYLON.VertexBuffer.UV2Kind
  60035. * - BABYLON.VertexBuffer.UV3Kind
  60036. * - BABYLON.VertexBuffer.UV4Kind
  60037. * - BABYLON.VertexBuffer.UV5Kind
  60038. * - BABYLON.VertexBuffer.UV6Kind
  60039. * - BABYLON.VertexBuffer.ColorKind
  60040. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60041. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60042. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60043. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60044. *
  60045. * Returns the Mesh.
  60046. */
  60047. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60048. if (this.sourceMesh) {
  60049. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60050. }
  60051. return this.sourceMesh;
  60052. };
  60053. /**
  60054. * Sets the mesh indices.
  60055. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60056. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60057. * This method creates a new index buffer each call.
  60058. * Returns the Mesh.
  60059. */
  60060. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60061. if (totalVertices === void 0) { totalVertices = null; }
  60062. if (this.sourceMesh) {
  60063. this.sourceMesh.setIndices(indices, totalVertices);
  60064. }
  60065. return this.sourceMesh;
  60066. };
  60067. /**
  60068. * Boolean : True if the mesh owns the requested kind of data.
  60069. */
  60070. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60071. return this._sourceMesh.isVerticesDataPresent(kind);
  60072. };
  60073. /**
  60074. * Returns an array of indices (IndicesArray).
  60075. */
  60076. InstancedMesh.prototype.getIndices = function () {
  60077. return this._sourceMesh.getIndices();
  60078. };
  60079. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60080. get: function () {
  60081. return this._sourceMesh._positions;
  60082. },
  60083. enumerable: true,
  60084. configurable: true
  60085. });
  60086. /**
  60087. * Sets a new updated BoundingInfo to the mesh.
  60088. * Returns the mesh.
  60089. */
  60090. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60091. var meshBB = this._sourceMesh.getBoundingInfo();
  60092. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60093. this._updateBoundingInfo();
  60094. return this;
  60095. };
  60096. InstancedMesh.prototype._preActivate = function () {
  60097. if (this._currentLOD) {
  60098. this._currentLOD._preActivate();
  60099. }
  60100. return this;
  60101. };
  60102. InstancedMesh.prototype._activate = function (renderId) {
  60103. if (this._currentLOD) {
  60104. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60105. }
  60106. return this;
  60107. };
  60108. /**
  60109. * Returns the current associated LOD AbstractMesh.
  60110. */
  60111. InstancedMesh.prototype.getLOD = function (camera) {
  60112. if (!camera) {
  60113. return this;
  60114. }
  60115. var boundingInfo = this.getBoundingInfo();
  60116. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60117. if (this._currentLOD === this.sourceMesh) {
  60118. return this;
  60119. }
  60120. return this._currentLOD;
  60121. };
  60122. InstancedMesh.prototype._syncSubMeshes = function () {
  60123. this.releaseSubMeshes();
  60124. if (this._sourceMesh.subMeshes) {
  60125. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60126. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60127. }
  60128. }
  60129. return this;
  60130. };
  60131. InstancedMesh.prototype._generatePointsArray = function () {
  60132. return this._sourceMesh._generatePointsArray();
  60133. };
  60134. /**
  60135. * Creates a new InstancedMesh from the current mesh.
  60136. * - name (string) : the cloned mesh name
  60137. * - newParent (optional Node) : the optional Node to parent the clone to.
  60138. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60139. *
  60140. * Returns the clone.
  60141. */
  60142. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60143. var result = this._sourceMesh.createInstance(name);
  60144. // Deep copy
  60145. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60146. // Bounding info
  60147. this.refreshBoundingInfo();
  60148. // Parent
  60149. if (newParent) {
  60150. result.parent = newParent;
  60151. }
  60152. if (!doNotCloneChildren) {
  60153. // Children
  60154. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60155. var mesh = this.getScene().meshes[index];
  60156. if (mesh.parent === this) {
  60157. mesh.clone(mesh.name, result);
  60158. }
  60159. }
  60160. }
  60161. result.computeWorldMatrix(true);
  60162. return result;
  60163. };
  60164. /**
  60165. * Disposes the InstancedMesh.
  60166. * Returns nothing.
  60167. */
  60168. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60169. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60170. // Remove from mesh
  60171. var index = this._sourceMesh.instances.indexOf(this);
  60172. this._sourceMesh.instances.splice(index, 1);
  60173. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60174. };
  60175. return InstancedMesh;
  60176. }(BABYLON.AbstractMesh));
  60177. BABYLON.InstancedMesh = InstancedMesh;
  60178. })(BABYLON || (BABYLON = {}));
  60179. //# sourceMappingURL=babylon.instancedMesh.js.map
  60180. var BABYLON;
  60181. (function (BABYLON) {
  60182. var LinesMesh = /** @class */ (function (_super) {
  60183. __extends(LinesMesh, _super);
  60184. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60185. if (scene === void 0) { scene = null; }
  60186. if (parent === void 0) { parent = null; }
  60187. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60188. _this.useVertexColor = useVertexColor;
  60189. _this.useVertexAlpha = useVertexAlpha;
  60190. _this.color = new BABYLON.Color3(1, 1, 1);
  60191. _this.alpha = 1;
  60192. if (source) {
  60193. _this.color = source.color.clone();
  60194. _this.alpha = source.alpha;
  60195. _this.useVertexColor = source.useVertexColor;
  60196. _this.useVertexAlpha = source.useVertexAlpha;
  60197. }
  60198. _this._intersectionThreshold = 0.1;
  60199. var defines = [];
  60200. var options = {
  60201. attributes: [BABYLON.VertexBuffer.PositionKind],
  60202. uniforms: ["world", "viewProjection"],
  60203. needAlphaBlending: true,
  60204. defines: defines
  60205. };
  60206. if (useVertexAlpha === false) {
  60207. options.needAlphaBlending = false;
  60208. }
  60209. if (!useVertexColor) {
  60210. options.uniforms.push("color");
  60211. }
  60212. else {
  60213. options.defines.push("#define VERTEXCOLOR");
  60214. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60215. }
  60216. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60217. return _this;
  60218. }
  60219. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60220. /**
  60221. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60222. * This margin is expressed in world space coordinates, so its value may vary.
  60223. * Default value is 0.1
  60224. * @returns the intersection Threshold value.
  60225. */
  60226. get: function () {
  60227. return this._intersectionThreshold;
  60228. },
  60229. /**
  60230. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60231. * This margin is expressed in world space coordinates, so its value may vary.
  60232. * @param value the new threshold to apply
  60233. */
  60234. set: function (value) {
  60235. if (this._intersectionThreshold === value) {
  60236. return;
  60237. }
  60238. this._intersectionThreshold = value;
  60239. if (this.geometry) {
  60240. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60241. }
  60242. },
  60243. enumerable: true,
  60244. configurable: true
  60245. });
  60246. /**
  60247. * Returns the string "LineMesh"
  60248. */
  60249. LinesMesh.prototype.getClassName = function () {
  60250. return "LinesMesh";
  60251. };
  60252. Object.defineProperty(LinesMesh.prototype, "material", {
  60253. get: function () {
  60254. return this._colorShader;
  60255. },
  60256. set: function (value) {
  60257. // Do nothing
  60258. },
  60259. enumerable: true,
  60260. configurable: true
  60261. });
  60262. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60263. get: function () {
  60264. return false;
  60265. },
  60266. enumerable: true,
  60267. configurable: true
  60268. });
  60269. LinesMesh.prototype.createInstance = function (name) {
  60270. throw new Error("LinesMeshes do not support createInstance.");
  60271. };
  60272. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60273. if (!this._geometry) {
  60274. return this;
  60275. }
  60276. // VBOs
  60277. this._geometry._bind(this._colorShader.getEffect());
  60278. // Color
  60279. if (!this.useVertexColor) {
  60280. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60281. }
  60282. return this;
  60283. };
  60284. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60285. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60286. return this;
  60287. }
  60288. var engine = this.getScene().getEngine();
  60289. // Draw order
  60290. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60291. return this;
  60292. };
  60293. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60294. this._colorShader.dispose();
  60295. _super.prototype.dispose.call(this, doNotRecurse);
  60296. };
  60297. /**
  60298. * Returns a new LineMesh object cloned from the current one.
  60299. */
  60300. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60301. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60302. };
  60303. return LinesMesh;
  60304. }(BABYLON.Mesh));
  60305. BABYLON.LinesMesh = LinesMesh;
  60306. })(BABYLON || (BABYLON = {}));
  60307. //# sourceMappingURL=babylon.linesMesh.js.map
  60308. var BABYLON;
  60309. (function (BABYLON) {
  60310. /**
  60311. * Class containing static functions to help procedurally build meshes
  60312. */
  60313. var MeshBuilder = /** @class */ (function () {
  60314. function MeshBuilder() {
  60315. }
  60316. MeshBuilder.updateSideOrientation = function (orientation) {
  60317. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60318. return BABYLON.Mesh.DOUBLESIDE;
  60319. }
  60320. if (orientation === undefined || orientation === null) {
  60321. return BABYLON.Mesh.FRONTSIDE;
  60322. }
  60323. return orientation;
  60324. };
  60325. /**
  60326. * Creates a box mesh
  60327. * * The parameter `size` sets the size (float) of each box side (default 1)
  60328. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60329. * * 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)
  60330. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60331. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60332. * * 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
  60333. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60334. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60335. * @param name defines the name of the mesh
  60336. * @param options defines the options used to create the mesh
  60337. * @param scene defines the hosting scene
  60338. * @returns the box mesh
  60339. */
  60340. MeshBuilder.CreateBox = function (name, options, scene) {
  60341. if (scene === void 0) { scene = null; }
  60342. var box = new BABYLON.Mesh(name, scene);
  60343. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60344. box._originalBuilderSideOrientation = options.sideOrientation;
  60345. var vertexData = BABYLON.VertexData.CreateBox(options);
  60346. vertexData.applyToMesh(box, options.updatable);
  60347. return box;
  60348. };
  60349. /**
  60350. * Creates a sphere mesh
  60351. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60352. * * 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`)
  60353. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60354. * * 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
  60355. * * 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)
  60356. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60357. * * 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
  60358. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60359. * @param name defines the name of the mesh
  60360. * @param options defines the options used to create the mesh
  60361. * @param scene defines the hosting scene
  60362. * @returns the sphere mesh
  60363. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60364. */
  60365. MeshBuilder.CreateSphere = function (name, options, scene) {
  60366. var sphere = new BABYLON.Mesh(name, scene);
  60367. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60368. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60369. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60370. vertexData.applyToMesh(sphere, options.updatable);
  60371. return sphere;
  60372. };
  60373. /**
  60374. * Creates a plane polygonal mesh. By default, this is a disc
  60375. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60376. * * 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
  60377. * * 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
  60378. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60379. * * 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
  60380. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60381. * @param name defines the name of the mesh
  60382. * @param options defines the options used to create the mesh
  60383. * @param scene defines the hosting scene
  60384. * @returns the plane polygonal mesh
  60385. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60386. */
  60387. MeshBuilder.CreateDisc = function (name, options, scene) {
  60388. if (scene === void 0) { scene = null; }
  60389. var disc = new BABYLON.Mesh(name, scene);
  60390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60391. disc._originalBuilderSideOrientation = options.sideOrientation;
  60392. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60393. vertexData.applyToMesh(disc, options.updatable);
  60394. return disc;
  60395. };
  60396. /**
  60397. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60398. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60399. * * 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`)
  60400. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60401. * * 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
  60402. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60403. * * 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
  60404. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60405. * @param name defines the name of the mesh
  60406. * @param options defines the options used to create the mesh
  60407. * @param scene defines the hosting scene
  60408. * @returns the icosahedron mesh
  60409. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60410. */
  60411. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60412. var sphere = new BABYLON.Mesh(name, scene);
  60413. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60414. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60415. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60416. vertexData.applyToMesh(sphere, options.updatable);
  60417. return sphere;
  60418. };
  60419. ;
  60420. /**
  60421. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60422. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60423. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60424. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60425. * * 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
  60426. * * 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
  60427. * * 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
  60428. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60429. * * 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
  60430. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60431. * * 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
  60432. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60433. * * 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
  60434. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60435. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60436. * @param name defines the name of the mesh
  60437. * @param options defines the options used to create the mesh
  60438. * @param scene defines the hosting scene
  60439. * @returns the ribbon mesh
  60440. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60441. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60442. */
  60443. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60444. if (scene === void 0) { scene = null; }
  60445. var pathArray = options.pathArray;
  60446. var closeArray = options.closeArray;
  60447. var closePath = options.closePath;
  60448. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60449. var instance = options.instance;
  60450. var updatable = options.updatable;
  60451. if (instance) { // existing ribbon instance update
  60452. // positionFunction : ribbon case
  60453. // only pathArray and sideOrientation parameters are taken into account for positions update
  60454. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60455. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60456. var positionFunction = function (positions) {
  60457. var minlg = pathArray[0].length;
  60458. var i = 0;
  60459. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60460. for (var si = 1; si <= ns; si++) {
  60461. for (var p = 0; p < pathArray.length; p++) {
  60462. var path = pathArray[p];
  60463. var l = path.length;
  60464. minlg = (minlg < l) ? minlg : l;
  60465. var j = 0;
  60466. while (j < minlg) {
  60467. positions[i] = path[j].x;
  60468. positions[i + 1] = path[j].y;
  60469. positions[i + 2] = path[j].z;
  60470. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60471. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60472. }
  60473. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60474. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60475. }
  60476. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60477. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60478. }
  60479. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60480. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60481. }
  60482. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60483. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60484. }
  60485. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60486. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60487. }
  60488. j++;
  60489. i += 3;
  60490. }
  60491. if (instance._closePath) {
  60492. positions[i] = path[0].x;
  60493. positions[i + 1] = path[0].y;
  60494. positions[i + 2] = path[0].z;
  60495. i += 3;
  60496. }
  60497. }
  60498. }
  60499. };
  60500. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60501. positionFunction(positions);
  60502. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60503. instance._boundingInfo.update(instance._worldMatrix);
  60504. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60505. if (options.colors) {
  60506. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60507. for (var c = 0; c < options.colors.length; c++) {
  60508. colors[c * 4] = options.colors[c].r;
  60509. colors[c * 4 + 1] = options.colors[c].g;
  60510. colors[c * 4 + 2] = options.colors[c].b;
  60511. colors[c * 4 + 3] = options.colors[c].a;
  60512. }
  60513. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60514. }
  60515. if (options.uvs) {
  60516. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60517. for (var i = 0; i < options.uvs.length; i++) {
  60518. uvs[i * 2] = options.uvs[i].x;
  60519. uvs[i * 2 + 1] = options.uvs[i].y;
  60520. }
  60521. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60522. }
  60523. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60524. var indices = instance.getIndices();
  60525. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60526. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60527. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60528. if (instance._closePath) {
  60529. var indexFirst = 0;
  60530. var indexLast = 0;
  60531. for (var p = 0; p < pathArray.length; p++) {
  60532. indexFirst = instance._idx[p] * 3;
  60533. if (p + 1 < pathArray.length) {
  60534. indexLast = (instance._idx[p + 1] - 1) * 3;
  60535. }
  60536. else {
  60537. indexLast = normals.length - 3;
  60538. }
  60539. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60540. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60541. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60542. normals[indexLast] = normals[indexFirst];
  60543. normals[indexLast + 1] = normals[indexFirst + 1];
  60544. normals[indexLast + 2] = normals[indexFirst + 2];
  60545. }
  60546. }
  60547. if (!(instance.areNormalsFrozen)) {
  60548. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60549. }
  60550. }
  60551. return instance;
  60552. }
  60553. else { // new ribbon creation
  60554. var ribbon = new BABYLON.Mesh(name, scene);
  60555. ribbon._originalBuilderSideOrientation = sideOrientation;
  60556. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60557. if (closePath) {
  60558. ribbon._idx = vertexData._idx;
  60559. }
  60560. ribbon._closePath = closePath;
  60561. ribbon._closeArray = closeArray;
  60562. vertexData.applyToMesh(ribbon, updatable);
  60563. return ribbon;
  60564. }
  60565. };
  60566. /**
  60567. * Creates a cylinder or a cone mesh
  60568. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60569. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60570. * * 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.
  60571. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60572. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60573. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60574. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60575. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60576. * * 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).
  60577. * * 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
  60578. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60579. * * 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
  60580. * * 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.
  60581. * * If `enclose` is false, a ring surface is one element.
  60582. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60583. * * 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
  60584. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60585. * * 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
  60586. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60587. * @param name defines the name of the mesh
  60588. * @param options defines the options used to create the mesh
  60589. * @param scene defines the hosting scene
  60590. * @returns the cylinder mesh
  60591. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60592. */
  60593. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60594. var cylinder = new BABYLON.Mesh(name, scene);
  60595. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60596. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60597. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60598. vertexData.applyToMesh(cylinder, options.updatable);
  60599. return cylinder;
  60600. };
  60601. /**
  60602. * Creates a torus mesh
  60603. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60604. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60605. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60606. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60607. * * 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
  60608. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60609. * @param name defines the name of the mesh
  60610. * @param options defines the options used to create the mesh
  60611. * @param scene defines the hosting scene
  60612. * @returns the torus mesh
  60613. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60614. */
  60615. MeshBuilder.CreateTorus = function (name, options, scene) {
  60616. var torus = new BABYLON.Mesh(name, scene);
  60617. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60618. torus._originalBuilderSideOrientation = options.sideOrientation;
  60619. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60620. vertexData.applyToMesh(torus, options.updatable);
  60621. return torus;
  60622. };
  60623. /**
  60624. * Creates a torus knot mesh
  60625. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60626. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60627. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60628. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60629. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60630. * * 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
  60631. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60632. * @param name defines the name of the mesh
  60633. * @param options defines the options used to create the mesh
  60634. * @param scene defines the hosting scene
  60635. * @returns the torus knot mesh
  60636. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60637. */
  60638. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60639. var torusKnot = new BABYLON.Mesh(name, scene);
  60640. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60641. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60642. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60643. vertexData.applyToMesh(torusKnot, options.updatable);
  60644. return torusKnot;
  60645. };
  60646. /**
  60647. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60648. * * 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
  60649. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60650. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60651. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60652. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60653. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60654. * * 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
  60655. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60656. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60657. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60658. * @param name defines the name of the new line system
  60659. * @param options defines the options used to create the line system
  60660. * @param scene defines the hosting scene
  60661. * @returns a new line system mesh
  60662. */
  60663. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60664. var instance = options.instance;
  60665. var lines = options.lines;
  60666. var colors = options.colors;
  60667. if (instance) { // lines update
  60668. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60669. var vertexColor;
  60670. var lineColors;
  60671. if (colors) {
  60672. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60673. }
  60674. var i = 0;
  60675. var c = 0;
  60676. for (var l = 0; l < lines.length; l++) {
  60677. var points = lines[l];
  60678. for (var p = 0; p < points.length; p++) {
  60679. positions[i] = points[p].x;
  60680. positions[i + 1] = points[p].y;
  60681. positions[i + 2] = points[p].z;
  60682. if (colors && vertexColor) {
  60683. lineColors = colors[l];
  60684. vertexColor[c] = lineColors[p].r;
  60685. vertexColor[c + 1] = lineColors[p].g;
  60686. vertexColor[c + 2] = lineColors[p].b;
  60687. vertexColor[c + 3] = lineColors[p].a;
  60688. c += 4;
  60689. }
  60690. i += 3;
  60691. }
  60692. }
  60693. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60694. if (colors && vertexColor) {
  60695. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60696. }
  60697. return instance;
  60698. }
  60699. // line system creation
  60700. var useVertexColor = (colors) ? true : false;
  60701. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60702. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60703. vertexData.applyToMesh(lineSystem, options.updatable);
  60704. return lineSystem;
  60705. };
  60706. /**
  60707. * Creates a line mesh
  60708. * 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
  60709. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60710. * * The parameter `points` is an array successive Vector3
  60711. * * 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
  60712. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60713. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60714. * * When updating an instance, remember that only point positions can change, not the number of points
  60715. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60716. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60717. * @param name defines the name of the new line system
  60718. * @param options defines the options used to create the line system
  60719. * @param scene defines the hosting scene
  60720. * @returns a new line mesh
  60721. */
  60722. MeshBuilder.CreateLines = function (name, options, scene) {
  60723. if (scene === void 0) { scene = null; }
  60724. var colors = (options.colors) ? [options.colors] : null;
  60725. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60726. return lines;
  60727. };
  60728. /**
  60729. * Creates a dashed line mesh
  60730. * * 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
  60731. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60732. * * The parameter `points` is an array successive Vector3
  60733. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60734. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60735. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60736. * * 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
  60737. * * When updating an instance, remember that only point positions can change, not the number of points
  60738. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60739. * @param name defines the name of the mesh
  60740. * @param options defines the options used to create the mesh
  60741. * @param scene defines the hosting scene
  60742. * @returns the dashed line mesh
  60743. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60744. */
  60745. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60746. if (scene === void 0) { scene = null; }
  60747. var points = options.points;
  60748. var instance = options.instance;
  60749. var gapSize = options.gapSize || 1;
  60750. var dashSize = options.dashSize || 3;
  60751. if (instance) { // dashed lines update
  60752. var positionFunction = function (positions) {
  60753. var curvect = BABYLON.Vector3.Zero();
  60754. var nbSeg = positions.length / 6;
  60755. var lg = 0;
  60756. var nb = 0;
  60757. var shft = 0;
  60758. var dashshft = 0;
  60759. var curshft = 0;
  60760. var p = 0;
  60761. var i = 0;
  60762. var j = 0;
  60763. for (i = 0; i < points.length - 1; i++) {
  60764. points[i + 1].subtractToRef(points[i], curvect);
  60765. lg += curvect.length();
  60766. }
  60767. shft = lg / nbSeg;
  60768. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60769. for (i = 0; i < points.length - 1; i++) {
  60770. points[i + 1].subtractToRef(points[i], curvect);
  60771. nb = Math.floor(curvect.length() / shft);
  60772. curvect.normalize();
  60773. j = 0;
  60774. while (j < nb && p < positions.length) {
  60775. curshft = shft * j;
  60776. positions[p] = points[i].x + curshft * curvect.x;
  60777. positions[p + 1] = points[i].y + curshft * curvect.y;
  60778. positions[p + 2] = points[i].z + curshft * curvect.z;
  60779. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60780. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60781. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60782. p += 6;
  60783. j++;
  60784. }
  60785. }
  60786. while (p < positions.length) {
  60787. positions[p] = points[i].x;
  60788. positions[p + 1] = points[i].y;
  60789. positions[p + 2] = points[i].z;
  60790. p += 3;
  60791. }
  60792. };
  60793. instance.updateMeshPositions(positionFunction, false);
  60794. return instance;
  60795. }
  60796. // dashed lines creation
  60797. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60798. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60799. vertexData.applyToMesh(dashedLines, options.updatable);
  60800. dashedLines.dashSize = dashSize;
  60801. dashedLines.gapSize = gapSize;
  60802. return dashedLines;
  60803. };
  60804. /**
  60805. * 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.
  60806. * * 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.
  60807. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60808. * * 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.
  60809. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60810. * * 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
  60811. * * 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
  60812. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60813. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60814. * * 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
  60815. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60816. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60817. * @param name defines the name of the mesh
  60818. * @param options defines the options used to create the mesh
  60819. * @param scene defines the hosting scene
  60820. * @returns the extruded shape mesh
  60821. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60822. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60823. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60824. */
  60825. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60826. if (scene === void 0) { scene = null; }
  60827. var path = options.path;
  60828. var shape = options.shape;
  60829. var scale = options.scale || 1;
  60830. var rotation = options.rotation || 0;
  60831. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60832. var updatable = options.updatable;
  60833. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60834. var instance = options.instance || null;
  60835. var invertUV = options.invertUV || false;
  60836. 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);
  60837. };
  60838. /**
  60839. * Creates an custom extruded shape mesh.
  60840. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60841. * * 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.
  60842. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60843. * * 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
  60844. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60845. * * 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
  60846. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60847. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60848. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60849. * * 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
  60850. * * 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
  60851. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60852. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60853. * * 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
  60854. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60855. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60856. * @param name defines the name of the mesh
  60857. * @param options defines the options used to create the mesh
  60858. * @param scene defines the hosting scene
  60859. * @returns the custom extruded shape mesh
  60860. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60861. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60862. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60863. */
  60864. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60865. var path = options.path;
  60866. var shape = options.shape;
  60867. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60868. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60869. var ribbonCloseArray = options.ribbonCloseArray || false;
  60870. var ribbonClosePath = options.ribbonClosePath || false;
  60871. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60872. var updatable = options.updatable;
  60873. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60874. var instance = options.instance;
  60875. var invertUV = options.invertUV || false;
  60876. 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);
  60877. };
  60878. /**
  60879. * Creates lathe mesh.
  60880. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60881. * * 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
  60882. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60883. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60884. * * 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
  60885. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60886. * * 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
  60887. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60888. * * 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
  60889. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60890. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60891. * @param name defines the name of the mesh
  60892. * @param options defines the options used to create the mesh
  60893. * @param scene defines the hosting scene
  60894. * @returns the lathe mesh
  60895. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60896. */
  60897. MeshBuilder.CreateLathe = function (name, options, scene) {
  60898. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60899. var closed = (options.closed === undefined) ? true : options.closed;
  60900. var shape = options.shape;
  60901. var radius = options.radius || 1;
  60902. var tessellation = options.tessellation || 64;
  60903. var updatable = options.updatable;
  60904. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60905. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60906. var pi2 = Math.PI * 2;
  60907. var paths = new Array();
  60908. var invertUV = options.invertUV || false;
  60909. var i = 0;
  60910. var p = 0;
  60911. var step = pi2 / tessellation * arc;
  60912. var rotated;
  60913. var path = new Array();
  60914. for (i = 0; i <= tessellation; i++) {
  60915. var path = [];
  60916. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60917. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60918. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60919. }
  60920. for (p = 0; p < shape.length; p++) {
  60921. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60922. path.push(rotated);
  60923. }
  60924. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60925. 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));
  60926. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60927. }
  60928. paths.push(path);
  60929. }
  60930. // lathe ribbon
  60931. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60932. return lathe;
  60933. };
  60934. /**
  60935. * Creates a plane mesh
  60936. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60937. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60938. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60939. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60940. * * 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
  60941. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60942. * @param name defines the name of the mesh
  60943. * @param options defines the options used to create the mesh
  60944. * @param scene defines the hosting scene
  60945. * @returns the plane mesh
  60946. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60947. */
  60948. MeshBuilder.CreatePlane = function (name, options, scene) {
  60949. var plane = new BABYLON.Mesh(name, scene);
  60950. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60951. plane._originalBuilderSideOrientation = options.sideOrientation;
  60952. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60953. vertexData.applyToMesh(plane, options.updatable);
  60954. if (options.sourcePlane) {
  60955. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60956. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60957. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60958. plane.rotate(vectorProduct, product);
  60959. }
  60960. return plane;
  60961. };
  60962. /**
  60963. * Creates a ground mesh
  60964. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60965. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60966. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60967. * @param name defines the name of the mesh
  60968. * @param options defines the options used to create the mesh
  60969. * @param scene defines the hosting scene
  60970. * @returns the ground mesh
  60971. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60972. */
  60973. MeshBuilder.CreateGround = function (name, options, scene) {
  60974. var ground = new BABYLON.GroundMesh(name, scene);
  60975. ground._setReady(false);
  60976. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60977. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60978. ground._width = options.width || 1;
  60979. ground._height = options.height || 1;
  60980. ground._maxX = ground._width / 2;
  60981. ground._maxZ = ground._height / 2;
  60982. ground._minX = -ground._maxX;
  60983. ground._minZ = -ground._maxZ;
  60984. var vertexData = BABYLON.VertexData.CreateGround(options);
  60985. vertexData.applyToMesh(ground, options.updatable);
  60986. ground._setReady(true);
  60987. return ground;
  60988. };
  60989. /**
  60990. * Creates a tiled ground mesh
  60991. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60992. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60993. * * 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
  60994. * * 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
  60995. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60996. * @param name defines the name of the mesh
  60997. * @param options defines the options used to create the mesh
  60998. * @param scene defines the hosting scene
  60999. * @returns the tiled ground mesh
  61000. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61001. */
  61002. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61003. var tiledGround = new BABYLON.Mesh(name, scene);
  61004. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61005. vertexData.applyToMesh(tiledGround, options.updatable);
  61006. return tiledGround;
  61007. };
  61008. /**
  61009. * Creates a ground mesh from a height map
  61010. * * The parameter `url` sets the URL of the height map image resource.
  61011. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61012. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61013. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61014. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61015. * * 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.
  61016. * * 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).
  61017. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61018. * @param name defines the name of the mesh
  61019. * @param url defines the url to the height map
  61020. * @param options defines the options used to create the mesh
  61021. * @param scene defines the hosting scene
  61022. * @returns the ground mesh
  61023. * @see http://doc.babylonjs.com/babylon101/height_map
  61024. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61025. */
  61026. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61027. var width = options.width || 10.0;
  61028. var height = options.height || 10.0;
  61029. var subdivisions = options.subdivisions || 1 | 0;
  61030. var minHeight = options.minHeight || 0.0;
  61031. var maxHeight = options.maxHeight || 1.0;
  61032. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61033. var updatable = options.updatable;
  61034. var onReady = options.onReady;
  61035. var ground = new BABYLON.GroundMesh(name, scene);
  61036. ground._subdivisionsX = subdivisions;
  61037. ground._subdivisionsY = subdivisions;
  61038. ground._width = width;
  61039. ground._height = height;
  61040. ground._maxX = ground._width / 2.0;
  61041. ground._maxZ = ground._height / 2.0;
  61042. ground._minX = -ground._maxX;
  61043. ground._minZ = -ground._maxZ;
  61044. ground._setReady(false);
  61045. var onload = function (img) {
  61046. // Getting height map data
  61047. var canvas = document.createElement("canvas");
  61048. var context = canvas.getContext("2d");
  61049. if (!context) {
  61050. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61051. }
  61052. if (scene.isDisposed) {
  61053. return;
  61054. }
  61055. var bufferWidth = img.width;
  61056. var bufferHeight = img.height;
  61057. canvas.width = bufferWidth;
  61058. canvas.height = bufferHeight;
  61059. context.drawImage(img, 0, 0);
  61060. // Create VertexData from map data
  61061. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61062. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61063. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61064. width: width, height: height,
  61065. subdivisions: subdivisions,
  61066. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61067. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61068. });
  61069. vertexData.applyToMesh(ground, updatable);
  61070. //execute ready callback, if set
  61071. if (onReady) {
  61072. onReady(ground);
  61073. }
  61074. ground._setReady(true);
  61075. };
  61076. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61077. return ground;
  61078. };
  61079. /**
  61080. * Creates a polygon mesh
  61081. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61082. * * 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
  61083. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61084. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61085. * * 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)
  61086. * * Remember you can only change the shape positions, not their number when updating a polygon
  61087. * @param name defines the name of the mesh
  61088. * @param options defines the options used to create the mesh
  61089. * @param scene defines the hosting scene
  61090. * @returns the polygon mesh
  61091. */
  61092. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61093. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61094. var shape = options.shape;
  61095. var holes = options.holes || [];
  61096. var depth = options.depth || 0;
  61097. var contours = [];
  61098. var hole = [];
  61099. for (var i = 0; i < shape.length; i++) {
  61100. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61101. }
  61102. var epsilon = 0.00000001;
  61103. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61104. contours.pop();
  61105. }
  61106. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61107. for (var hNb = 0; hNb < holes.length; hNb++) {
  61108. hole = [];
  61109. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61110. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61111. }
  61112. polygonTriangulation.addHole(hole);
  61113. }
  61114. var polygon = polygonTriangulation.build(options.updatable, depth);
  61115. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61116. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61117. vertexData.applyToMesh(polygon, options.updatable);
  61118. return polygon;
  61119. };
  61120. ;
  61121. /**
  61122. * Creates an extruded polygon mesh, with depth in the Y direction.
  61123. * * 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)
  61124. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61125. * @param name defines the name of the mesh
  61126. * @param options defines the options used to create the mesh
  61127. * @param scene defines the hosting scene
  61128. * @returns the polygon mesh
  61129. */
  61130. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61131. return MeshBuilder.CreatePolygon(name, options, scene);
  61132. };
  61133. ;
  61134. /**
  61135. * Creates a tube mesh.
  61136. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61137. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61138. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61139. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61140. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61141. * * 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)
  61142. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61143. * * 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
  61144. * * 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
  61145. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61146. * * 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
  61147. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61148. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61149. * @param name defines the name of the mesh
  61150. * @param options defines the options used to create the mesh
  61151. * @param scene defines the hosting scene
  61152. * @returns the tube mesh
  61153. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61154. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61155. */
  61156. MeshBuilder.CreateTube = function (name, options, scene) {
  61157. var path = options.path;
  61158. var instance = options.instance;
  61159. var radius = 1.0;
  61160. if (instance) {
  61161. radius = instance.radius;
  61162. }
  61163. if (options.radius !== undefined) {
  61164. radius = options.radius;
  61165. }
  61166. ;
  61167. var tessellation = options.tessellation || 64 | 0;
  61168. var radiusFunction = options.radiusFunction || null;
  61169. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61170. var invertUV = options.invertUV || false;
  61171. var updatable = options.updatable;
  61172. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61173. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61174. // tube geometry
  61175. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61176. var tangents = path3D.getTangents();
  61177. var normals = path3D.getNormals();
  61178. var distances = path3D.getDistances();
  61179. var pi2 = Math.PI * 2;
  61180. var step = pi2 / tessellation * arc;
  61181. var returnRadius = function () { return radius; };
  61182. var radiusFunctionFinal = radiusFunction || returnRadius;
  61183. var circlePath;
  61184. var rad;
  61185. var normal;
  61186. var rotated;
  61187. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61188. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61189. for (var i = 0; i < path.length; i++) {
  61190. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61191. circlePath = Array(); // current circle array
  61192. normal = normals[i]; // current normal
  61193. for (var t = 0; t < tessellation; t++) {
  61194. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61195. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61196. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61197. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61198. circlePath[t] = rotated;
  61199. }
  61200. circlePaths[index] = circlePath;
  61201. index++;
  61202. }
  61203. // cap
  61204. var capPath = function (nbPoints, pathIndex) {
  61205. var pointCap = Array();
  61206. for (var i = 0; i < nbPoints; i++) {
  61207. pointCap.push(path[pathIndex]);
  61208. }
  61209. return pointCap;
  61210. };
  61211. switch (cap) {
  61212. case BABYLON.Mesh.NO_CAP:
  61213. break;
  61214. case BABYLON.Mesh.CAP_START:
  61215. circlePaths[0] = capPath(tessellation, 0);
  61216. circlePaths[1] = circlePaths[2].slice(0);
  61217. break;
  61218. case BABYLON.Mesh.CAP_END:
  61219. circlePaths[index] = circlePaths[index - 1].slice(0);
  61220. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61221. break;
  61222. case BABYLON.Mesh.CAP_ALL:
  61223. circlePaths[0] = capPath(tessellation, 0);
  61224. circlePaths[1] = circlePaths[2].slice(0);
  61225. circlePaths[index] = circlePaths[index - 1].slice(0);
  61226. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61227. break;
  61228. default:
  61229. break;
  61230. }
  61231. return circlePaths;
  61232. };
  61233. var path3D;
  61234. var pathArray;
  61235. if (instance) { // tube update
  61236. var arc = options.arc || instance.arc;
  61237. path3D = (instance.path3D).update(path);
  61238. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61239. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61240. instance.path3D = path3D;
  61241. instance.pathArray = pathArray;
  61242. instance.arc = arc;
  61243. instance.radius = radius;
  61244. return instance;
  61245. }
  61246. // tube creation
  61247. path3D = new BABYLON.Path3D(path);
  61248. var newPathArray = new Array();
  61249. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61250. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61251. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61252. tube.pathArray = pathArray;
  61253. tube.path3D = path3D;
  61254. tube.tessellation = tessellation;
  61255. tube.cap = cap;
  61256. tube.arc = options.arc;
  61257. tube.radius = radius;
  61258. return tube;
  61259. };
  61260. /**
  61261. * Creates a polyhedron mesh
  61262. * * 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
  61263. * * The parameter `size` (positive float, default 1) sets the polygon size
  61264. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61265. * * 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`
  61266. * * 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
  61267. * * 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)`)
  61268. * * 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
  61269. * * 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
  61270. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61271. * * 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
  61272. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61273. * @param name defines the name of the mesh
  61274. * @param options defines the options used to create the mesh
  61275. * @param scene defines the hosting scene
  61276. * @returns the polyhedron mesh
  61277. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61278. */
  61279. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61280. var polyhedron = new BABYLON.Mesh(name, scene);
  61281. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61282. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61283. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61284. vertexData.applyToMesh(polyhedron, options.updatable);
  61285. return polyhedron;
  61286. };
  61287. /**
  61288. * Creates a decal mesh.
  61289. * 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
  61290. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61291. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61292. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61293. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61294. * @param name defines the name of the mesh
  61295. * @param sourceMesh defines the mesh where the decal must be applied
  61296. * @param options defines the options used to create the mesh
  61297. * @param scene defines the hosting scene
  61298. * @returns the decal mesh
  61299. * @see http://doc.babylonjs.com/how_to/decals
  61300. */
  61301. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61302. var indices = sourceMesh.getIndices();
  61303. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61304. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61305. var position = options.position || BABYLON.Vector3.Zero();
  61306. var normal = options.normal || BABYLON.Vector3.Up();
  61307. var size = options.size || BABYLON.Vector3.One();
  61308. var angle = options.angle || 0;
  61309. // Getting correct rotation
  61310. if (!normal) {
  61311. var target = new BABYLON.Vector3(0, 0, 1);
  61312. var camera = sourceMesh.getScene().activeCamera;
  61313. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61314. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61315. }
  61316. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61317. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61318. var pitch = Math.atan2(normal.y, len);
  61319. // Matrix
  61320. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61321. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61322. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61323. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61324. var vertexData = new BABYLON.VertexData();
  61325. vertexData.indices = [];
  61326. vertexData.positions = [];
  61327. vertexData.normals = [];
  61328. vertexData.uvs = [];
  61329. var currentVertexDataIndex = 0;
  61330. var extractDecalVector3 = function (indexId) {
  61331. var result = new BABYLON.PositionNormalVertex();
  61332. if (!indices || !positions || !normals) {
  61333. return result;
  61334. }
  61335. var vertexId = indices[indexId];
  61336. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61337. // Send vector to decal local world
  61338. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61339. // Get normal
  61340. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61341. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61342. return result;
  61343. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61344. var clip = function (vertices, axis) {
  61345. if (vertices.length === 0) {
  61346. return vertices;
  61347. }
  61348. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61349. var clipVertices = function (v0, v1) {
  61350. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61351. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61352. };
  61353. var result = new Array();
  61354. for (var index = 0; index < vertices.length; index += 3) {
  61355. var v1Out;
  61356. var v2Out;
  61357. var v3Out;
  61358. var total = 0;
  61359. var nV1 = null;
  61360. var nV2 = null;
  61361. var nV3 = null;
  61362. var nV4 = null;
  61363. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61364. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61365. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61366. v1Out = d1 > 0;
  61367. v2Out = d2 > 0;
  61368. v3Out = d3 > 0;
  61369. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61370. switch (total) {
  61371. case 0:
  61372. result.push(vertices[index]);
  61373. result.push(vertices[index + 1]);
  61374. result.push(vertices[index + 2]);
  61375. break;
  61376. case 1:
  61377. if (v1Out) {
  61378. nV1 = vertices[index + 1];
  61379. nV2 = vertices[index + 2];
  61380. nV3 = clipVertices(vertices[index], nV1);
  61381. nV4 = clipVertices(vertices[index], nV2);
  61382. }
  61383. if (v2Out) {
  61384. nV1 = vertices[index];
  61385. nV2 = vertices[index + 2];
  61386. nV3 = clipVertices(vertices[index + 1], nV1);
  61387. nV4 = clipVertices(vertices[index + 1], nV2);
  61388. result.push(nV3);
  61389. result.push(nV2.clone());
  61390. result.push(nV1.clone());
  61391. result.push(nV2.clone());
  61392. result.push(nV3.clone());
  61393. result.push(nV4);
  61394. break;
  61395. }
  61396. if (v3Out) {
  61397. nV1 = vertices[index];
  61398. nV2 = vertices[index + 1];
  61399. nV3 = clipVertices(vertices[index + 2], nV1);
  61400. nV4 = clipVertices(vertices[index + 2], nV2);
  61401. }
  61402. if (nV1 && nV2 && nV3 && nV4) {
  61403. result.push(nV1.clone());
  61404. result.push(nV2.clone());
  61405. result.push(nV3);
  61406. result.push(nV4);
  61407. result.push(nV3.clone());
  61408. result.push(nV2.clone());
  61409. }
  61410. break;
  61411. case 2:
  61412. if (!v1Out) {
  61413. nV1 = vertices[index].clone();
  61414. nV2 = clipVertices(nV1, vertices[index + 1]);
  61415. nV3 = clipVertices(nV1, vertices[index + 2]);
  61416. result.push(nV1);
  61417. result.push(nV2);
  61418. result.push(nV3);
  61419. }
  61420. if (!v2Out) {
  61421. nV1 = vertices[index + 1].clone();
  61422. nV2 = clipVertices(nV1, vertices[index + 2]);
  61423. nV3 = clipVertices(nV1, vertices[index]);
  61424. result.push(nV1);
  61425. result.push(nV2);
  61426. result.push(nV3);
  61427. }
  61428. if (!v3Out) {
  61429. nV1 = vertices[index + 2].clone();
  61430. nV2 = clipVertices(nV1, vertices[index]);
  61431. nV3 = clipVertices(nV1, vertices[index + 1]);
  61432. result.push(nV1);
  61433. result.push(nV2);
  61434. result.push(nV3);
  61435. }
  61436. break;
  61437. case 3:
  61438. break;
  61439. }
  61440. }
  61441. return result;
  61442. };
  61443. for (var index = 0; index < indices.length; index += 3) {
  61444. var faceVertices = new Array();
  61445. faceVertices.push(extractDecalVector3(index));
  61446. faceVertices.push(extractDecalVector3(index + 1));
  61447. faceVertices.push(extractDecalVector3(index + 2));
  61448. // Clip
  61449. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61450. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61451. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61452. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61453. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61454. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61455. if (faceVertices.length === 0) {
  61456. continue;
  61457. }
  61458. // Add UVs and get back to world
  61459. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61460. var vertex = faceVertices[vIndex];
  61461. //TODO check for Int32Array | Uint32Array | Uint16Array
  61462. vertexData.indices.push(currentVertexDataIndex);
  61463. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61464. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61465. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61466. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61467. currentVertexDataIndex++;
  61468. }
  61469. }
  61470. // Return mesh
  61471. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61472. vertexData.applyToMesh(decal);
  61473. decal.position = position.clone();
  61474. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61475. return decal;
  61476. };
  61477. // Privates
  61478. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61479. // extrusion geometry
  61480. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61481. var tangents = path3D.getTangents();
  61482. var normals = path3D.getNormals();
  61483. var binormals = path3D.getBinormals();
  61484. var distances = path3D.getDistances();
  61485. var angle = 0;
  61486. var returnScale = function () { return scale !== null ? scale : 1; };
  61487. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61488. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61489. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61490. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61491. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61492. for (var i = 0; i < curve.length; i++) {
  61493. var shapePath = new Array();
  61494. var angleStep = rotate(i, distances[i]);
  61495. var scaleRatio = scl(i, distances[i]);
  61496. for (var p = 0; p < shape.length; p++) {
  61497. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61498. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61499. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61500. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61501. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61502. shapePath[p] = rotated;
  61503. }
  61504. shapePaths[index] = shapePath;
  61505. angle += angleStep;
  61506. index++;
  61507. }
  61508. // cap
  61509. var capPath = function (shapePath) {
  61510. var pointCap = Array();
  61511. var barycenter = BABYLON.Vector3.Zero();
  61512. var i;
  61513. for (i = 0; i < shapePath.length; i++) {
  61514. barycenter.addInPlace(shapePath[i]);
  61515. }
  61516. barycenter.scaleInPlace(1.0 / shapePath.length);
  61517. for (i = 0; i < shapePath.length; i++) {
  61518. pointCap.push(barycenter);
  61519. }
  61520. return pointCap;
  61521. };
  61522. switch (cap) {
  61523. case BABYLON.Mesh.NO_CAP:
  61524. break;
  61525. case BABYLON.Mesh.CAP_START:
  61526. shapePaths[0] = capPath(shapePaths[2]);
  61527. shapePaths[1] = shapePaths[2];
  61528. break;
  61529. case BABYLON.Mesh.CAP_END:
  61530. shapePaths[index] = shapePaths[index - 1];
  61531. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61532. break;
  61533. case BABYLON.Mesh.CAP_ALL:
  61534. shapePaths[0] = capPath(shapePaths[2]);
  61535. shapePaths[1] = shapePaths[2];
  61536. shapePaths[index] = shapePaths[index - 1];
  61537. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61538. break;
  61539. default:
  61540. break;
  61541. }
  61542. return shapePaths;
  61543. };
  61544. var path3D;
  61545. var pathArray;
  61546. if (instance) { // instance update
  61547. path3D = (instance.path3D).update(curve);
  61548. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61549. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61550. return instance;
  61551. }
  61552. // extruded shape creation
  61553. path3D = new BABYLON.Path3D(curve);
  61554. var newShapePaths = new Array();
  61555. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61556. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61557. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61558. extrudedGeneric.pathArray = pathArray;
  61559. extrudedGeneric.path3D = path3D;
  61560. extrudedGeneric.cap = cap;
  61561. return extrudedGeneric;
  61562. };
  61563. return MeshBuilder;
  61564. }());
  61565. BABYLON.MeshBuilder = MeshBuilder;
  61566. })(BABYLON || (BABYLON = {}));
  61567. //# sourceMappingURL=babylon.meshBuilder.js.map
  61568. var BABYLON;
  61569. (function (BABYLON) {
  61570. /**
  61571. * Draco compression (https://google.github.io/draco/)
  61572. *
  61573. * This class wraps the Draco module.
  61574. *
  61575. * **Encoder**
  61576. *
  61577. * The encoder is not currently implemented.
  61578. *
  61579. * **Decoder**
  61580. *
  61581. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61582. *
  61583. * To update the configuration, use the following code:
  61584. * ```javascript
  61585. * BABYLON.DracoCompression.Configuration = {
  61586. * decoder: {
  61587. * wasmUrl: "<url to the WebAssembly library>",
  61588. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61589. * fallbackUrl: "<url to the fallback JavaScript library>",
  61590. * }
  61591. * };
  61592. * ```
  61593. *
  61594. * 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.
  61595. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61596. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61597. *
  61598. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61599. * ```javascript
  61600. * var dracoCompression = new BABYLON.DracoCompression();
  61601. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61602. * [BABYLON.VertexBuffer.PositionKind]: 0
  61603. * });
  61604. * ```
  61605. *
  61606. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61607. */
  61608. var DracoCompression = /** @class */ (function () {
  61609. /**
  61610. * Constructor
  61611. */
  61612. function DracoCompression() {
  61613. }
  61614. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61615. /**
  61616. * Returns true if the decoder is available.
  61617. */
  61618. get: function () {
  61619. if (typeof DracoDecoderModule !== "undefined") {
  61620. return true;
  61621. }
  61622. var decoder = DracoCompression.Configuration.decoder;
  61623. if (decoder) {
  61624. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61625. return true;
  61626. }
  61627. if (decoder.fallbackUrl) {
  61628. return true;
  61629. }
  61630. }
  61631. return false;
  61632. },
  61633. enumerable: true,
  61634. configurable: true
  61635. });
  61636. /**
  61637. * Stop all async operations and release resources.
  61638. */
  61639. DracoCompression.prototype.dispose = function () {
  61640. };
  61641. /**
  61642. * Decode Draco compressed mesh data to vertex data.
  61643. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61644. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61645. * @returns A promise that resolves with the decoded vertex data
  61646. */
  61647. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61648. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61649. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61650. var module = wrappedModule.module;
  61651. var vertexData = new BABYLON.VertexData();
  61652. var buffer = new module.DecoderBuffer();
  61653. buffer.Init(dataView, dataView.byteLength);
  61654. var decoder = new module.Decoder();
  61655. var geometry;
  61656. var status;
  61657. try {
  61658. var type = decoder.GetEncodedGeometryType(buffer);
  61659. switch (type) {
  61660. case module.TRIANGULAR_MESH:
  61661. geometry = new module.Mesh();
  61662. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61663. break;
  61664. case module.POINT_CLOUD:
  61665. geometry = new module.PointCloud();
  61666. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61667. break;
  61668. default:
  61669. throw new Error("Invalid geometry type " + type);
  61670. }
  61671. if (!status.ok() || !geometry.ptr) {
  61672. throw new Error(status.error_msg());
  61673. }
  61674. var numPoints = geometry.num_points();
  61675. if (type === module.TRIANGULAR_MESH) {
  61676. var numFaces = geometry.num_faces();
  61677. var faceIndices = new module.DracoInt32Array();
  61678. try {
  61679. var indices = new Uint32Array(numFaces * 3);
  61680. for (var i = 0; i < numFaces; i++) {
  61681. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61682. var offset = i * 3;
  61683. indices[offset + 0] = faceIndices.GetValue(0);
  61684. indices[offset + 1] = faceIndices.GetValue(1);
  61685. indices[offset + 2] = faceIndices.GetValue(2);
  61686. }
  61687. vertexData.indices = indices;
  61688. }
  61689. finally {
  61690. module.destroy(faceIndices);
  61691. }
  61692. }
  61693. for (var kind in attributes) {
  61694. var uniqueId = attributes[kind];
  61695. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61696. var dracoData = new module.DracoFloat32Array();
  61697. try {
  61698. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61699. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61700. for (var i = 0; i < babylonData.length; i++) {
  61701. babylonData[i] = dracoData.GetValue(i);
  61702. }
  61703. vertexData.set(babylonData, kind);
  61704. }
  61705. finally {
  61706. module.destroy(dracoData);
  61707. }
  61708. }
  61709. }
  61710. finally {
  61711. if (geometry) {
  61712. module.destroy(geometry);
  61713. }
  61714. module.destroy(decoder);
  61715. module.destroy(buffer);
  61716. }
  61717. return vertexData;
  61718. });
  61719. };
  61720. DracoCompression._GetDecoderModule = function () {
  61721. if (!DracoCompression._DecoderModulePromise) {
  61722. var promise = null;
  61723. var config_1 = {};
  61724. if (typeof DracoDecoderModule !== "undefined") {
  61725. promise = Promise.resolve();
  61726. }
  61727. else {
  61728. var decoder = DracoCompression.Configuration.decoder;
  61729. if (decoder) {
  61730. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61731. promise = Promise.all([
  61732. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61733. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61734. config_1.wasmBinary = data;
  61735. })
  61736. ]);
  61737. }
  61738. else if (decoder.fallbackUrl) {
  61739. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61740. }
  61741. }
  61742. }
  61743. if (!promise) {
  61744. throw new Error("Draco decoder module is not available");
  61745. }
  61746. DracoCompression._DecoderModulePromise = promise.then(function () {
  61747. return new Promise(function (resolve) {
  61748. config_1.onModuleLoaded = function (decoderModule) {
  61749. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61750. resolve({ module: decoderModule });
  61751. };
  61752. DracoDecoderModule(config_1);
  61753. });
  61754. });
  61755. }
  61756. return DracoCompression._DecoderModulePromise;
  61757. };
  61758. DracoCompression._LoadScriptAsync = function (url) {
  61759. return new Promise(function (resolve, reject) {
  61760. BABYLON.Tools.LoadScript(url, function () {
  61761. resolve();
  61762. }, function (message) {
  61763. reject(new Error(message));
  61764. });
  61765. });
  61766. };
  61767. DracoCompression._LoadFileAsync = function (url) {
  61768. return new Promise(function (resolve, reject) {
  61769. BABYLON.Tools.LoadFile(url, function (data) {
  61770. resolve(data);
  61771. }, undefined, undefined, true, function (request, exception) {
  61772. reject(exception);
  61773. });
  61774. });
  61775. };
  61776. /**
  61777. * The configuration. Defaults to the following urls:
  61778. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  61779. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  61780. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61781. */
  61782. DracoCompression.Configuration = {
  61783. decoder: {
  61784. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61785. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61786. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61787. }
  61788. };
  61789. return DracoCompression;
  61790. }());
  61791. BABYLON.DracoCompression = DracoCompression;
  61792. })(BABYLON || (BABYLON = {}));
  61793. //# sourceMappingURL=babylon.dracoCompression.js.map
  61794. var BABYLON;
  61795. (function (BABYLON) {
  61796. var AudioEngine = /** @class */ (function () {
  61797. function AudioEngine() {
  61798. this._audioContext = null;
  61799. this._audioContextInitialized = false;
  61800. this.canUseWebAudio = false;
  61801. this.WarnedWebAudioUnsupported = false;
  61802. this.unlocked = false;
  61803. this.isMP3supported = false;
  61804. this.isOGGsupported = false;
  61805. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61806. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61807. this.canUseWebAudio = true;
  61808. }
  61809. var audioElem = document.createElement('audio');
  61810. try {
  61811. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61812. this.isMP3supported = true;
  61813. }
  61814. }
  61815. catch (e) {
  61816. // protect error during capability check.
  61817. }
  61818. try {
  61819. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61820. this.isOGGsupported = true;
  61821. }
  61822. }
  61823. catch (e) {
  61824. // protect error during capability check.
  61825. }
  61826. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61827. this._unlockiOSaudio();
  61828. }
  61829. else {
  61830. this.unlocked = true;
  61831. }
  61832. }
  61833. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61834. get: function () {
  61835. if (!this._audioContextInitialized) {
  61836. this._initializeAudioContext();
  61837. }
  61838. return this._audioContext;
  61839. },
  61840. enumerable: true,
  61841. configurable: true
  61842. });
  61843. AudioEngine.prototype._unlockiOSaudio = function () {
  61844. var _this = this;
  61845. var unlockaudio = function () {
  61846. if (!_this.audioContext) {
  61847. return;
  61848. }
  61849. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61850. var source = _this.audioContext.createBufferSource();
  61851. source.buffer = buffer;
  61852. source.connect(_this.audioContext.destination);
  61853. source.start(0);
  61854. setTimeout(function () {
  61855. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61856. _this.unlocked = true;
  61857. window.removeEventListener('touchend', unlockaudio, false);
  61858. if (_this.onAudioUnlocked) {
  61859. _this.onAudioUnlocked();
  61860. }
  61861. }
  61862. }, 0);
  61863. };
  61864. window.addEventListener('touchend', unlockaudio, false);
  61865. };
  61866. AudioEngine.prototype._initializeAudioContext = function () {
  61867. try {
  61868. if (this.canUseWebAudio) {
  61869. this._audioContext = new AudioContext();
  61870. // create a global volume gain node
  61871. this.masterGain = this._audioContext.createGain();
  61872. this.masterGain.gain.value = 1;
  61873. this.masterGain.connect(this._audioContext.destination);
  61874. this._audioContextInitialized = true;
  61875. }
  61876. }
  61877. catch (e) {
  61878. this.canUseWebAudio = false;
  61879. BABYLON.Tools.Error("Web Audio: " + e.message);
  61880. }
  61881. };
  61882. AudioEngine.prototype.dispose = function () {
  61883. if (this.canUseWebAudio && this._audioContextInitialized) {
  61884. if (this._connectedAnalyser && this._audioContext) {
  61885. this._connectedAnalyser.stopDebugCanvas();
  61886. this._connectedAnalyser.dispose();
  61887. this.masterGain.disconnect();
  61888. this.masterGain.connect(this._audioContext.destination);
  61889. this._connectedAnalyser = null;
  61890. }
  61891. this.masterGain.gain.value = 1;
  61892. }
  61893. this.WarnedWebAudioUnsupported = false;
  61894. };
  61895. AudioEngine.prototype.getGlobalVolume = function () {
  61896. if (this.canUseWebAudio && this._audioContextInitialized) {
  61897. return this.masterGain.gain.value;
  61898. }
  61899. else {
  61900. return -1;
  61901. }
  61902. };
  61903. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61904. if (this.canUseWebAudio && this._audioContextInitialized) {
  61905. this.masterGain.gain.value = newVolume;
  61906. }
  61907. };
  61908. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61909. if (this._connectedAnalyser) {
  61910. this._connectedAnalyser.stopDebugCanvas();
  61911. }
  61912. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61913. this._connectedAnalyser = analyser;
  61914. this.masterGain.disconnect();
  61915. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61916. }
  61917. };
  61918. return AudioEngine;
  61919. }());
  61920. BABYLON.AudioEngine = AudioEngine;
  61921. })(BABYLON || (BABYLON = {}));
  61922. //# sourceMappingURL=babylon.audioEngine.js.map
  61923. var BABYLON;
  61924. (function (BABYLON) {
  61925. var Sound = /** @class */ (function () {
  61926. /**
  61927. * Create a sound and attach it to a scene
  61928. * @param name Name of your sound
  61929. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  61930. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61931. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61932. */
  61933. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61934. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61935. var _this = this;
  61936. this.autoplay = false;
  61937. this.loop = false;
  61938. this.useCustomAttenuation = false;
  61939. this.spatialSound = false;
  61940. this.refDistance = 1;
  61941. this.rolloffFactor = 1;
  61942. this.maxDistance = 100;
  61943. this.distanceModel = "linear";
  61944. this._panningModel = "equalpower";
  61945. this._playbackRate = 1;
  61946. this._streaming = false;
  61947. this._startTime = 0;
  61948. this._startOffset = 0;
  61949. this._position = BABYLON.Vector3.Zero();
  61950. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61951. this._volume = 1;
  61952. this._isReadyToPlay = false;
  61953. this.isPlaying = false;
  61954. this.isPaused = false;
  61955. this._isDirectional = false;
  61956. // Used if you'd like to create a directional sound.
  61957. // If not set, the sound will be omnidirectional
  61958. this._coneInnerAngle = 360;
  61959. this._coneOuterAngle = 360;
  61960. this._coneOuterGain = 0;
  61961. this._isOutputConnected = false;
  61962. this._urlType = "Unknown";
  61963. this.name = name;
  61964. this._scene = scene;
  61965. this._readyToPlayCallback = readyToPlayCallback;
  61966. // Default custom attenuation function is a linear attenuation
  61967. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61968. if (currentDistance < maxDistance) {
  61969. return currentVolume * (1 - currentDistance / maxDistance);
  61970. }
  61971. else {
  61972. return 0;
  61973. }
  61974. };
  61975. if (options) {
  61976. this.autoplay = options.autoplay || false;
  61977. this.loop = options.loop || false;
  61978. // if volume === 0, we need another way to check this option
  61979. if (options.volume !== undefined) {
  61980. this._volume = options.volume;
  61981. }
  61982. this.spatialSound = options.spatialSound || false;
  61983. this.maxDistance = options.maxDistance || 100;
  61984. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61985. this.rolloffFactor = options.rolloffFactor || 1;
  61986. this.refDistance = options.refDistance || 1;
  61987. this.distanceModel = options.distanceModel || "linear";
  61988. this._playbackRate = options.playbackRate || 1;
  61989. this._streaming = options.streaming || false;
  61990. }
  61991. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61992. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61993. this._soundGain.gain.value = this._volume;
  61994. this._inputAudioNode = this._soundGain;
  61995. this._ouputAudioNode = this._soundGain;
  61996. if (this.spatialSound) {
  61997. this._createSpatialParameters();
  61998. }
  61999. this._scene.mainSoundTrack.AddSound(this);
  62000. var validParameter = true;
  62001. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62002. if (urlOrArrayBuffer) {
  62003. try {
  62004. if (typeof (urlOrArrayBuffer) === "string") {
  62005. this._urlType = "String";
  62006. }
  62007. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62008. this._urlType = "ArrayBuffer";
  62009. }
  62010. else if (urlOrArrayBuffer instanceof MediaStream) {
  62011. this._urlType = "MediaStream";
  62012. }
  62013. else if (Array.isArray(urlOrArrayBuffer)) {
  62014. this._urlType = "Array";
  62015. }
  62016. var urls = [];
  62017. var codecSupportedFound = false;
  62018. switch (this._urlType) {
  62019. case "MediaStream":
  62020. this._streaming = true;
  62021. this._isReadyToPlay = true;
  62022. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62023. if (this.autoplay) {
  62024. this.play();
  62025. }
  62026. if (this._readyToPlayCallback) {
  62027. this._readyToPlayCallback();
  62028. }
  62029. break;
  62030. case "ArrayBuffer":
  62031. if (urlOrArrayBuffer.byteLength > 0) {
  62032. codecSupportedFound = true;
  62033. this._soundLoaded(urlOrArrayBuffer);
  62034. }
  62035. break;
  62036. case "String":
  62037. urls.push(urlOrArrayBuffer);
  62038. case "Array":
  62039. if (urls.length === 0)
  62040. urls = urlOrArrayBuffer;
  62041. // If we found a supported format, we load it immediately and stop the loop
  62042. for (var i = 0; i < urls.length; i++) {
  62043. var url = urls[i];
  62044. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62045. codecSupportedFound = true;
  62046. }
  62047. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62048. codecSupportedFound = true;
  62049. }
  62050. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62051. codecSupportedFound = true;
  62052. }
  62053. if (url.indexOf("blob:") !== -1) {
  62054. codecSupportedFound = true;
  62055. }
  62056. if (codecSupportedFound) {
  62057. // Loading sound using XHR2
  62058. if (!this._streaming) {
  62059. this._scene._loadFile(url, function (data) {
  62060. _this._soundLoaded(data);
  62061. }, undefined, true, true, function (exception) {
  62062. if (exception) {
  62063. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62064. }
  62065. BABYLON.Tools.Error("Sound creation aborted.");
  62066. _this._scene.mainSoundTrack.RemoveSound(_this);
  62067. });
  62068. }
  62069. // Streaming sound using HTML5 Audio tag
  62070. else {
  62071. this._htmlAudioElement = new Audio(url);
  62072. this._htmlAudioElement.controls = false;
  62073. this._htmlAudioElement.loop = this.loop;
  62074. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62075. this._htmlAudioElement.preload = "auto";
  62076. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62077. _this._isReadyToPlay = true;
  62078. if (_this.autoplay) {
  62079. _this.play();
  62080. }
  62081. if (_this._readyToPlayCallback) {
  62082. _this._readyToPlayCallback();
  62083. }
  62084. });
  62085. document.body.appendChild(this._htmlAudioElement);
  62086. }
  62087. break;
  62088. }
  62089. }
  62090. break;
  62091. default:
  62092. validParameter = false;
  62093. break;
  62094. }
  62095. if (!validParameter) {
  62096. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62097. }
  62098. else {
  62099. if (!codecSupportedFound) {
  62100. this._isReadyToPlay = true;
  62101. // Simulating a ready to play event to avoid breaking code path
  62102. if (this._readyToPlayCallback) {
  62103. window.setTimeout(function () {
  62104. if (_this._readyToPlayCallback) {
  62105. _this._readyToPlayCallback();
  62106. }
  62107. }, 1000);
  62108. }
  62109. }
  62110. }
  62111. }
  62112. catch (ex) {
  62113. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62114. this._scene.mainSoundTrack.RemoveSound(this);
  62115. }
  62116. }
  62117. }
  62118. else {
  62119. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62120. this._scene.mainSoundTrack.AddSound(this);
  62121. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62122. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62123. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62124. }
  62125. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62126. if (this._readyToPlayCallback) {
  62127. window.setTimeout(function () {
  62128. if (_this._readyToPlayCallback) {
  62129. _this._readyToPlayCallback();
  62130. }
  62131. }, 1000);
  62132. }
  62133. }
  62134. }
  62135. Sound.prototype.dispose = function () {
  62136. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62137. if (this.isPlaying) {
  62138. this.stop();
  62139. }
  62140. this._isReadyToPlay = false;
  62141. if (this.soundTrackId === -1) {
  62142. this._scene.mainSoundTrack.RemoveSound(this);
  62143. }
  62144. else {
  62145. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62146. }
  62147. if (this._soundGain) {
  62148. this._soundGain.disconnect();
  62149. this._soundGain = null;
  62150. }
  62151. if (this._soundPanner) {
  62152. this._soundPanner.disconnect();
  62153. this._soundPanner = null;
  62154. }
  62155. if (this._soundSource) {
  62156. this._soundSource.disconnect();
  62157. this._soundSource = null;
  62158. }
  62159. this._audioBuffer = null;
  62160. if (this._htmlAudioElement) {
  62161. this._htmlAudioElement.pause();
  62162. this._htmlAudioElement.src = "";
  62163. document.body.removeChild(this._htmlAudioElement);
  62164. }
  62165. if (this._streamingSource) {
  62166. this._streamingSource.disconnect();
  62167. }
  62168. if (this._connectedMesh && this._registerFunc) {
  62169. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62170. this._connectedMesh = null;
  62171. }
  62172. }
  62173. };
  62174. Sound.prototype.isReady = function () {
  62175. return this._isReadyToPlay;
  62176. };
  62177. Sound.prototype._soundLoaded = function (audioData) {
  62178. var _this = this;
  62179. if (!BABYLON.Engine.audioEngine.audioContext) {
  62180. return;
  62181. }
  62182. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62183. _this._audioBuffer = buffer;
  62184. _this._isReadyToPlay = true;
  62185. if (_this.autoplay) {
  62186. _this.play();
  62187. }
  62188. if (_this._readyToPlayCallback) {
  62189. _this._readyToPlayCallback();
  62190. }
  62191. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62192. };
  62193. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62194. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62195. this._audioBuffer = audioBuffer;
  62196. this._isReadyToPlay = true;
  62197. }
  62198. };
  62199. Sound.prototype.updateOptions = function (options) {
  62200. if (options) {
  62201. this.loop = options.loop || this.loop;
  62202. this.maxDistance = options.maxDistance || this.maxDistance;
  62203. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62204. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62205. this.refDistance = options.refDistance || this.refDistance;
  62206. this.distanceModel = options.distanceModel || this.distanceModel;
  62207. this._playbackRate = options.playbackRate || this._playbackRate;
  62208. this._updateSpatialParameters();
  62209. if (this.isPlaying) {
  62210. if (this._streaming && this._htmlAudioElement) {
  62211. this._htmlAudioElement.playbackRate = this._playbackRate;
  62212. }
  62213. else {
  62214. if (this._soundSource) {
  62215. this._soundSource.playbackRate.value = this._playbackRate;
  62216. }
  62217. }
  62218. }
  62219. }
  62220. };
  62221. Sound.prototype._createSpatialParameters = function () {
  62222. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62223. if (this._scene.headphone) {
  62224. this._panningModel = "HRTF";
  62225. }
  62226. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62227. this._updateSpatialParameters();
  62228. this._soundPanner.connect(this._ouputAudioNode);
  62229. this._inputAudioNode = this._soundPanner;
  62230. }
  62231. };
  62232. Sound.prototype._updateSpatialParameters = function () {
  62233. if (this.spatialSound && this._soundPanner) {
  62234. if (this.useCustomAttenuation) {
  62235. // Tricks to disable in a way embedded Web Audio attenuation
  62236. this._soundPanner.distanceModel = "linear";
  62237. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62238. this._soundPanner.refDistance = 1;
  62239. this._soundPanner.rolloffFactor = 1;
  62240. this._soundPanner.panningModel = this._panningModel;
  62241. }
  62242. else {
  62243. this._soundPanner.distanceModel = this.distanceModel;
  62244. this._soundPanner.maxDistance = this.maxDistance;
  62245. this._soundPanner.refDistance = this.refDistance;
  62246. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62247. this._soundPanner.panningModel = this._panningModel;
  62248. }
  62249. }
  62250. };
  62251. Sound.prototype.switchPanningModelToHRTF = function () {
  62252. this._panningModel = "HRTF";
  62253. this._switchPanningModel();
  62254. };
  62255. Sound.prototype.switchPanningModelToEqualPower = function () {
  62256. this._panningModel = "equalpower";
  62257. this._switchPanningModel();
  62258. };
  62259. Sound.prototype._switchPanningModel = function () {
  62260. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62261. this._soundPanner.panningModel = this._panningModel;
  62262. }
  62263. };
  62264. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62265. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62266. if (this._isOutputConnected) {
  62267. this._ouputAudioNode.disconnect();
  62268. }
  62269. this._ouputAudioNode.connect(soundTrackAudioNode);
  62270. this._isOutputConnected = true;
  62271. }
  62272. };
  62273. /**
  62274. * Transform this sound into a directional source
  62275. * @param coneInnerAngle Size of the inner cone in degree
  62276. * @param coneOuterAngle Size of the outer cone in degree
  62277. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62278. */
  62279. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62280. if (coneOuterAngle < coneInnerAngle) {
  62281. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62282. return;
  62283. }
  62284. this._coneInnerAngle = coneInnerAngle;
  62285. this._coneOuterAngle = coneOuterAngle;
  62286. this._coneOuterGain = coneOuterGain;
  62287. this._isDirectional = true;
  62288. if (this.isPlaying && this.loop) {
  62289. this.stop();
  62290. this.play();
  62291. }
  62292. };
  62293. Sound.prototype.setPosition = function (newPosition) {
  62294. this._position = newPosition;
  62295. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62296. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62297. }
  62298. };
  62299. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62300. this._localDirection = newLocalDirection;
  62301. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62302. this._updateDirection();
  62303. }
  62304. };
  62305. Sound.prototype._updateDirection = function () {
  62306. if (!this._connectedMesh || !this._soundPanner) {
  62307. return;
  62308. }
  62309. var mat = this._connectedMesh.getWorldMatrix();
  62310. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62311. direction.normalize();
  62312. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62313. };
  62314. Sound.prototype.updateDistanceFromListener = function () {
  62315. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62316. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62317. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62318. }
  62319. };
  62320. Sound.prototype.setAttenuationFunction = function (callback) {
  62321. this._customAttenuationFunction = callback;
  62322. };
  62323. /**
  62324. * Play the sound
  62325. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62326. * @param offset (optional) Start the sound setting it at a specific time
  62327. */
  62328. Sound.prototype.play = function (time, offset) {
  62329. var _this = this;
  62330. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62331. try {
  62332. if (this._startOffset < 0) {
  62333. time = -this._startOffset;
  62334. this._startOffset = 0;
  62335. }
  62336. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62337. if (!this._soundSource || !this._streamingSource) {
  62338. if (this.spatialSound && this._soundPanner) {
  62339. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62340. if (this._isDirectional) {
  62341. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62342. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62343. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62344. if (this._connectedMesh) {
  62345. this._updateDirection();
  62346. }
  62347. else {
  62348. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62349. }
  62350. }
  62351. }
  62352. }
  62353. if (this._streaming) {
  62354. if (!this._streamingSource) {
  62355. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62356. this._htmlAudioElement.onended = function () { _this._onended(); };
  62357. this._htmlAudioElement.playbackRate = this._playbackRate;
  62358. }
  62359. this._streamingSource.disconnect();
  62360. this._streamingSource.connect(this._inputAudioNode);
  62361. if (this._htmlAudioElement) {
  62362. this._htmlAudioElement.play();
  62363. }
  62364. }
  62365. else {
  62366. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62367. this._soundSource.buffer = this._audioBuffer;
  62368. this._soundSource.connect(this._inputAudioNode);
  62369. this._soundSource.loop = this.loop;
  62370. this._soundSource.playbackRate.value = this._playbackRate;
  62371. this._soundSource.onended = function () { _this._onended(); };
  62372. if (this._soundSource.buffer) {
  62373. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62374. }
  62375. }
  62376. this._startTime = startTime;
  62377. this.isPlaying = true;
  62378. this.isPaused = false;
  62379. }
  62380. catch (ex) {
  62381. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62382. }
  62383. }
  62384. };
  62385. Sound.prototype._onended = function () {
  62386. this.isPlaying = false;
  62387. if (this.onended) {
  62388. this.onended();
  62389. }
  62390. };
  62391. /**
  62392. * Stop the sound
  62393. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62394. */
  62395. Sound.prototype.stop = function (time) {
  62396. if (this.isPlaying) {
  62397. if (this._streaming) {
  62398. if (this._htmlAudioElement) {
  62399. this._htmlAudioElement.pause();
  62400. // Test needed for Firefox or it will generate an Invalid State Error
  62401. if (this._htmlAudioElement.currentTime > 0) {
  62402. this._htmlAudioElement.currentTime = 0;
  62403. }
  62404. }
  62405. else {
  62406. this._streamingSource.disconnect();
  62407. }
  62408. }
  62409. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62410. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62411. this._soundSource.stop(stopTime);
  62412. this._soundSource.onended = function () { };
  62413. if (!this.isPaused) {
  62414. this._startOffset = 0;
  62415. }
  62416. }
  62417. this.isPlaying = false;
  62418. }
  62419. };
  62420. Sound.prototype.pause = function () {
  62421. if (this.isPlaying) {
  62422. this.isPaused = true;
  62423. if (this._streaming) {
  62424. if (this._htmlAudioElement) {
  62425. this._htmlAudioElement.pause();
  62426. }
  62427. else {
  62428. this._streamingSource.disconnect();
  62429. }
  62430. }
  62431. else if (BABYLON.Engine.audioEngine.audioContext) {
  62432. this.stop(0);
  62433. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62434. }
  62435. }
  62436. };
  62437. Sound.prototype.setVolume = function (newVolume, time) {
  62438. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62439. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62440. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62441. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62442. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62443. }
  62444. else {
  62445. this._soundGain.gain.value = newVolume;
  62446. }
  62447. }
  62448. this._volume = newVolume;
  62449. };
  62450. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62451. this._playbackRate = newPlaybackRate;
  62452. if (this.isPlaying) {
  62453. if (this._streaming && this._htmlAudioElement) {
  62454. this._htmlAudioElement.playbackRate = this._playbackRate;
  62455. }
  62456. else if (this._soundSource) {
  62457. this._soundSource.playbackRate.value = this._playbackRate;
  62458. }
  62459. }
  62460. };
  62461. Sound.prototype.getVolume = function () {
  62462. return this._volume;
  62463. };
  62464. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62465. var _this = this;
  62466. if (this._connectedMesh && this._registerFunc) {
  62467. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62468. this._registerFunc = null;
  62469. }
  62470. this._connectedMesh = meshToConnectTo;
  62471. if (!this.spatialSound) {
  62472. this.spatialSound = true;
  62473. this._createSpatialParameters();
  62474. if (this.isPlaying && this.loop) {
  62475. this.stop();
  62476. this.play();
  62477. }
  62478. }
  62479. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62480. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62481. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62482. };
  62483. Sound.prototype.detachFromMesh = function () {
  62484. if (this._connectedMesh && this._registerFunc) {
  62485. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62486. this._registerFunc = null;
  62487. this._connectedMesh = null;
  62488. }
  62489. };
  62490. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62491. if (!node.getBoundingInfo) {
  62492. return;
  62493. }
  62494. var mesh = node;
  62495. var boundingInfo = mesh.getBoundingInfo();
  62496. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62497. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62498. this._updateDirection();
  62499. }
  62500. };
  62501. Sound.prototype.clone = function () {
  62502. var _this = this;
  62503. if (!this._streaming) {
  62504. var setBufferAndRun = function () {
  62505. if (_this._isReadyToPlay) {
  62506. clonedSound._audioBuffer = _this.getAudioBuffer();
  62507. clonedSound._isReadyToPlay = true;
  62508. if (clonedSound.autoplay) {
  62509. clonedSound.play();
  62510. }
  62511. }
  62512. else {
  62513. window.setTimeout(setBufferAndRun, 300);
  62514. }
  62515. };
  62516. var currentOptions = {
  62517. autoplay: this.autoplay, loop: this.loop,
  62518. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62519. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62520. refDistance: this.refDistance, distanceModel: this.distanceModel
  62521. };
  62522. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62523. if (this.useCustomAttenuation) {
  62524. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62525. }
  62526. clonedSound.setPosition(this._position);
  62527. clonedSound.setPlaybackRate(this._playbackRate);
  62528. setBufferAndRun();
  62529. return clonedSound;
  62530. }
  62531. // Can't clone a streaming sound
  62532. else {
  62533. return null;
  62534. }
  62535. };
  62536. Sound.prototype.getAudioBuffer = function () {
  62537. return this._audioBuffer;
  62538. };
  62539. Sound.prototype.serialize = function () {
  62540. var serializationObject = {
  62541. name: this.name,
  62542. url: this.name,
  62543. autoplay: this.autoplay,
  62544. loop: this.loop,
  62545. volume: this._volume,
  62546. spatialSound: this.spatialSound,
  62547. maxDistance: this.maxDistance,
  62548. rolloffFactor: this.rolloffFactor,
  62549. refDistance: this.refDistance,
  62550. distanceModel: this.distanceModel,
  62551. playbackRate: this._playbackRate,
  62552. panningModel: this._panningModel,
  62553. soundTrackId: this.soundTrackId
  62554. };
  62555. if (this.spatialSound) {
  62556. if (this._connectedMesh)
  62557. serializationObject.connectedMeshId = this._connectedMesh.id;
  62558. serializationObject.position = this._position.asArray();
  62559. serializationObject.refDistance = this.refDistance;
  62560. serializationObject.distanceModel = this.distanceModel;
  62561. serializationObject.isDirectional = this._isDirectional;
  62562. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62563. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62564. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62565. serializationObject.coneOuterGain = this._coneOuterGain;
  62566. }
  62567. return serializationObject;
  62568. };
  62569. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62570. var soundName = parsedSound.name;
  62571. var soundUrl;
  62572. if (parsedSound.url) {
  62573. soundUrl = rootUrl + parsedSound.url;
  62574. }
  62575. else {
  62576. soundUrl = rootUrl + soundName;
  62577. }
  62578. var options = {
  62579. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62580. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62581. rolloffFactor: parsedSound.rolloffFactor,
  62582. refDistance: parsedSound.refDistance,
  62583. distanceModel: parsedSound.distanceModel,
  62584. playbackRate: parsedSound.playbackRate
  62585. };
  62586. var newSound;
  62587. if (!sourceSound) {
  62588. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62589. scene._addPendingData(newSound);
  62590. }
  62591. else {
  62592. var setBufferAndRun = function () {
  62593. if (sourceSound._isReadyToPlay) {
  62594. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62595. newSound._isReadyToPlay = true;
  62596. if (newSound.autoplay) {
  62597. newSound.play();
  62598. }
  62599. }
  62600. else {
  62601. window.setTimeout(setBufferAndRun, 300);
  62602. }
  62603. };
  62604. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62605. setBufferAndRun();
  62606. }
  62607. if (parsedSound.position) {
  62608. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62609. newSound.setPosition(soundPosition);
  62610. }
  62611. if (parsedSound.isDirectional) {
  62612. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62613. if (parsedSound.localDirectionToMesh) {
  62614. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62615. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62616. }
  62617. }
  62618. if (parsedSound.connectedMeshId) {
  62619. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62620. if (connectedMesh) {
  62621. newSound.attachToMesh(connectedMesh);
  62622. }
  62623. }
  62624. return newSound;
  62625. };
  62626. return Sound;
  62627. }());
  62628. BABYLON.Sound = Sound;
  62629. })(BABYLON || (BABYLON = {}));
  62630. //# sourceMappingURL=babylon.sound.js.map
  62631. var BABYLON;
  62632. (function (BABYLON) {
  62633. var SoundTrack = /** @class */ (function () {
  62634. function SoundTrack(scene, options) {
  62635. this.id = -1;
  62636. this._isMainTrack = false;
  62637. this._isInitialized = false;
  62638. this._scene = scene;
  62639. this.soundCollection = new Array();
  62640. this._options = options;
  62641. if (!this._isMainTrack) {
  62642. this._scene.soundTracks.push(this);
  62643. this.id = this._scene.soundTracks.length - 1;
  62644. }
  62645. }
  62646. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62647. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62648. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62649. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62650. if (this._options) {
  62651. if (this._options.volume) {
  62652. this._outputAudioNode.gain.value = this._options.volume;
  62653. }
  62654. if (this._options.mainTrack) {
  62655. this._isMainTrack = this._options.mainTrack;
  62656. }
  62657. }
  62658. this._isInitialized = true;
  62659. }
  62660. };
  62661. SoundTrack.prototype.dispose = function () {
  62662. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62663. if (this._connectedAnalyser) {
  62664. this._connectedAnalyser.stopDebugCanvas();
  62665. }
  62666. while (this.soundCollection.length) {
  62667. this.soundCollection[0].dispose();
  62668. }
  62669. if (this._outputAudioNode) {
  62670. this._outputAudioNode.disconnect();
  62671. }
  62672. this._outputAudioNode = null;
  62673. }
  62674. };
  62675. SoundTrack.prototype.AddSound = function (sound) {
  62676. if (!this._isInitialized) {
  62677. this._initializeSoundTrackAudioGraph();
  62678. }
  62679. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62680. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62681. }
  62682. if (sound.soundTrackId) {
  62683. if (sound.soundTrackId === -1) {
  62684. this._scene.mainSoundTrack.RemoveSound(sound);
  62685. }
  62686. else {
  62687. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62688. }
  62689. }
  62690. this.soundCollection.push(sound);
  62691. sound.soundTrackId = this.id;
  62692. };
  62693. SoundTrack.prototype.RemoveSound = function (sound) {
  62694. var index = this.soundCollection.indexOf(sound);
  62695. if (index !== -1) {
  62696. this.soundCollection.splice(index, 1);
  62697. }
  62698. };
  62699. SoundTrack.prototype.setVolume = function (newVolume) {
  62700. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62701. this._outputAudioNode.gain.value = newVolume;
  62702. }
  62703. };
  62704. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62705. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62706. for (var i = 0; i < this.soundCollection.length; i++) {
  62707. this.soundCollection[i].switchPanningModelToHRTF();
  62708. }
  62709. }
  62710. };
  62711. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62712. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62713. for (var i = 0; i < this.soundCollection.length; i++) {
  62714. this.soundCollection[i].switchPanningModelToEqualPower();
  62715. }
  62716. }
  62717. };
  62718. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62719. if (this._connectedAnalyser) {
  62720. this._connectedAnalyser.stopDebugCanvas();
  62721. }
  62722. this._connectedAnalyser = analyser;
  62723. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62724. this._outputAudioNode.disconnect();
  62725. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62726. }
  62727. };
  62728. return SoundTrack;
  62729. }());
  62730. BABYLON.SoundTrack = SoundTrack;
  62731. })(BABYLON || (BABYLON = {}));
  62732. //# sourceMappingURL=babylon.soundtrack.js.map
  62733. var BABYLON;
  62734. (function (BABYLON) {
  62735. /**
  62736. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62737. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62738. */
  62739. var Analyser = /** @class */ (function () {
  62740. /**
  62741. * Creates a new analyser
  62742. * @param scene defines hosting scene
  62743. */
  62744. function Analyser(scene) {
  62745. /**
  62746. * Gets or sets the smoothing
  62747. * @ignorenaming
  62748. */
  62749. this.SMOOTHING = 0.75;
  62750. /**
  62751. * Gets or sets the FFT table size
  62752. * @ignorenaming
  62753. */
  62754. this.FFT_SIZE = 512;
  62755. /**
  62756. * Gets or sets the bar graph amplitude
  62757. * @ignorenaming
  62758. */
  62759. this.BARGRAPHAMPLITUDE = 256;
  62760. /**
  62761. * Gets or sets the position of the debug canvas
  62762. * @ignorenaming
  62763. */
  62764. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62765. /**
  62766. * Gets or sets the debug canvas size
  62767. * @ignorenaming
  62768. */
  62769. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62770. this._scene = scene;
  62771. this._audioEngine = BABYLON.Engine.audioEngine;
  62772. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62773. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62774. this._webAudioAnalyser.minDecibels = -140;
  62775. this._webAudioAnalyser.maxDecibels = 0;
  62776. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62777. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62778. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62779. }
  62780. }
  62781. /**
  62782. * Get the number of data values you will have to play with for the visualization
  62783. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62784. * @returns a number
  62785. */
  62786. Analyser.prototype.getFrequencyBinCount = function () {
  62787. if (this._audioEngine.canUseWebAudio) {
  62788. return this._webAudioAnalyser.frequencyBinCount;
  62789. }
  62790. else {
  62791. return 0;
  62792. }
  62793. };
  62794. /**
  62795. * Gets the current frequency data as a byte array
  62796. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62797. * @returns a Uint8Array
  62798. */
  62799. Analyser.prototype.getByteFrequencyData = function () {
  62800. if (this._audioEngine.canUseWebAudio) {
  62801. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62802. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62803. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62804. }
  62805. return this._byteFreqs;
  62806. };
  62807. /**
  62808. * Gets the current waveform as a byte array
  62809. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62810. * @returns a Uint8Array
  62811. */
  62812. Analyser.prototype.getByteTimeDomainData = function () {
  62813. if (this._audioEngine.canUseWebAudio) {
  62814. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62815. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62816. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62817. }
  62818. return this._byteTime;
  62819. };
  62820. /**
  62821. * Gets the current frequency data as a float array
  62822. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62823. * @returns a Float32Array
  62824. */
  62825. Analyser.prototype.getFloatFrequencyData = function () {
  62826. if (this._audioEngine.canUseWebAudio) {
  62827. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62828. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62829. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62830. }
  62831. return this._floatFreqs;
  62832. };
  62833. /**
  62834. * Renders the debug canvas
  62835. */
  62836. Analyser.prototype.drawDebugCanvas = function () {
  62837. var _this = this;
  62838. if (this._audioEngine.canUseWebAudio) {
  62839. if (!this._debugCanvas) {
  62840. this._debugCanvas = document.createElement("canvas");
  62841. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62842. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62843. this._debugCanvas.style.position = "absolute";
  62844. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62845. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62846. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62847. document.body.appendChild(this._debugCanvas);
  62848. this._registerFunc = function () {
  62849. _this.drawDebugCanvas();
  62850. };
  62851. this._scene.registerBeforeRender(this._registerFunc);
  62852. }
  62853. if (this._registerFunc && this._debugCanvasContext) {
  62854. var workingArray = this.getByteFrequencyData();
  62855. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62856. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62857. // Draw the frequency domain chart.
  62858. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62859. var value = workingArray[i];
  62860. var percent = value / this.BARGRAPHAMPLITUDE;
  62861. var height = this.DEBUGCANVASSIZE.height * percent;
  62862. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62863. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62864. var hue = i / this.getFrequencyBinCount() * 360;
  62865. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62866. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62867. }
  62868. }
  62869. }
  62870. };
  62871. /**
  62872. * Stops rendering the debug canvas and removes it
  62873. */
  62874. Analyser.prototype.stopDebugCanvas = function () {
  62875. if (this._debugCanvas) {
  62876. if (this._registerFunc) {
  62877. this._scene.unregisterBeforeRender(this._registerFunc);
  62878. this._registerFunc = null;
  62879. }
  62880. document.body.removeChild(this._debugCanvas);
  62881. this._debugCanvas = null;
  62882. this._debugCanvasContext = null;
  62883. }
  62884. };
  62885. /**
  62886. * Connects two audio nodes
  62887. * @param inputAudioNode defines first node to connect
  62888. * @param outputAudioNode defines second node to connect
  62889. */
  62890. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62891. if (this._audioEngine.canUseWebAudio) {
  62892. inputAudioNode.connect(this._webAudioAnalyser);
  62893. this._webAudioAnalyser.connect(outputAudioNode);
  62894. }
  62895. };
  62896. /**
  62897. * Releases all associated resources
  62898. */
  62899. Analyser.prototype.dispose = function () {
  62900. if (this._audioEngine.canUseWebAudio) {
  62901. this._webAudioAnalyser.disconnect();
  62902. }
  62903. };
  62904. return Analyser;
  62905. }());
  62906. BABYLON.Analyser = Analyser;
  62907. })(BABYLON || (BABYLON = {}));
  62908. //# sourceMappingURL=babylon.analyser.js.map
  62909. var BABYLON;
  62910. (function (BABYLON) {
  62911. var CubeTexture = /** @class */ (function (_super) {
  62912. __extends(CubeTexture, _super);
  62913. /**
  62914. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  62915. * as prefiltered data.
  62916. * @param rootUrl defines the url of the texture or the root name of the six images
  62917. * @param scene defines the scene the texture is attached to
  62918. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  62919. * @param noMipmap defines if mipmaps should be created or not
  62920. * @param files defines the six files to load for the different faces
  62921. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  62922. * @param onError defines a callback triggered in case of error during load
  62923. * @param format defines the internal format to use for the texture once loaded
  62924. * @param prefiltered defines whether or not the texture is created from prefiltered data
  62925. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  62926. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  62927. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  62928. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  62929. * @return the cube texture
  62930. */
  62931. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  62932. if (extensions === void 0) { extensions = null; }
  62933. if (noMipmap === void 0) { noMipmap = false; }
  62934. if (files === void 0) { files = null; }
  62935. if (onLoad === void 0) { onLoad = null; }
  62936. if (onError === void 0) { onError = null; }
  62937. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62938. if (prefiltered === void 0) { prefiltered = false; }
  62939. if (forcedExtension === void 0) { forcedExtension = null; }
  62940. if (createPolynomials === void 0) { createPolynomials = false; }
  62941. if (lodScale === void 0) { lodScale = 0.8; }
  62942. if (lodOffset === void 0) { lodOffset = 0; }
  62943. var _this = _super.call(this, scene) || this;
  62944. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62945. /**
  62946. * Gets or sets the center of the bounding box associated with the cube texture
  62947. * It must define where the camera used to render the texture was set
  62948. */
  62949. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62950. _this._rotationY = 0;
  62951. /** @hidden */
  62952. _this._prefiltered = false;
  62953. _this.name = rootUrl;
  62954. _this.url = rootUrl;
  62955. _this._noMipmap = noMipmap;
  62956. _this.hasAlpha = false;
  62957. _this._format = format;
  62958. _this.isCube = true;
  62959. _this._textureMatrix = BABYLON.Matrix.Identity();
  62960. _this._createPolynomials = createPolynomials;
  62961. if (!rootUrl && !files) {
  62962. return _this;
  62963. }
  62964. var lastDot = rootUrl.lastIndexOf(".");
  62965. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62966. var isDDS = (extension === ".dds");
  62967. var isEnv = (extension === ".env");
  62968. if (isEnv) {
  62969. _this.gammaSpace = false;
  62970. _this._prefiltered = false;
  62971. }
  62972. else {
  62973. _this._prefiltered = prefiltered;
  62974. if (prefiltered) {
  62975. _this.gammaSpace = false;
  62976. }
  62977. }
  62978. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62979. if (!files) {
  62980. if (!isEnv && !isDDS && !extensions) {
  62981. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62982. }
  62983. files = [];
  62984. if (extensions) {
  62985. for (var index = 0; index < extensions.length; index++) {
  62986. files.push(rootUrl + extensions[index]);
  62987. }
  62988. }
  62989. }
  62990. _this._files = files;
  62991. if (!_this._texture) {
  62992. if (!scene.useDelayedTextureLoading) {
  62993. if (prefiltered) {
  62994. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  62995. }
  62996. else {
  62997. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  62998. }
  62999. }
  63000. else {
  63001. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63002. }
  63003. }
  63004. else if (onLoad) {
  63005. if (_this._texture.isReady) {
  63006. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63007. }
  63008. else {
  63009. _this._texture.onLoadedObservable.add(onLoad);
  63010. }
  63011. }
  63012. return _this;
  63013. }
  63014. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63015. get: function () {
  63016. return this._boundingBoxSize;
  63017. },
  63018. /**
  63019. * Gets or sets the size of the bounding box associated with the cube texture
  63020. * When defined, the cubemap will switch to local mode
  63021. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63022. * @example https://www.babylonjs-playground.com/#RNASML
  63023. */
  63024. set: function (value) {
  63025. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63026. return;
  63027. }
  63028. this._boundingBoxSize = value;
  63029. var scene = this.getScene();
  63030. if (scene) {
  63031. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63032. }
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63038. /**
  63039. * Gets texture matrix rotation angle around Y axis radians.
  63040. */
  63041. get: function () {
  63042. return this._rotationY;
  63043. },
  63044. /**
  63045. * Sets texture matrix rotation angle around Y axis in radians.
  63046. */
  63047. set: function (value) {
  63048. this._rotationY = value;
  63049. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63050. },
  63051. enumerable: true,
  63052. configurable: true
  63053. });
  63054. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63055. var rootUrlKey = "";
  63056. files.forEach(function (url) { return rootUrlKey += url; });
  63057. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63058. };
  63059. /**
  63060. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63061. * @param url defines the url of the prefiltered texture
  63062. * @param scene defines the scene the texture is attached to
  63063. * @param forcedExtension defines the extension of the file if different from the url
  63064. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63065. * @return the prefiltered texture
  63066. */
  63067. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63068. if (forcedExtension === void 0) { forcedExtension = null; }
  63069. if (createPolynomials === void 0) { createPolynomials = true; }
  63070. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63071. };
  63072. // Methods
  63073. CubeTexture.prototype.delayLoad = function () {
  63074. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63075. return;
  63076. }
  63077. var scene = this.getScene();
  63078. if (!scene) {
  63079. return;
  63080. }
  63081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63082. this._texture = this._getFromCache(this.url, this._noMipmap);
  63083. if (!this._texture) {
  63084. if (this._prefiltered) {
  63085. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63086. }
  63087. else {
  63088. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63089. }
  63090. }
  63091. };
  63092. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63093. return this._textureMatrix;
  63094. };
  63095. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63096. this._textureMatrix = value;
  63097. };
  63098. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63099. var texture = BABYLON.SerializationHelper.Parse(function () {
  63100. var prefiltered = false;
  63101. if (parsedTexture.prefiltered) {
  63102. prefiltered = parsedTexture.prefiltered;
  63103. }
  63104. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63105. }, parsedTexture, scene);
  63106. // Local Cubemaps
  63107. if (parsedTexture.boundingBoxPosition) {
  63108. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63109. }
  63110. if (parsedTexture.boundingBoxSize) {
  63111. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63112. }
  63113. // Animations
  63114. if (parsedTexture.animations) {
  63115. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63116. var parsedAnimation = parsedTexture.animations[animationIndex];
  63117. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63118. }
  63119. }
  63120. return texture;
  63121. };
  63122. CubeTexture.prototype.clone = function () {
  63123. var _this = this;
  63124. return BABYLON.SerializationHelper.Clone(function () {
  63125. var scene = _this.getScene();
  63126. if (!scene) {
  63127. return _this;
  63128. }
  63129. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63130. }, this);
  63131. };
  63132. __decorate([
  63133. BABYLON.serialize("rotationY")
  63134. ], CubeTexture.prototype, "_rotationY", void 0);
  63135. return CubeTexture;
  63136. }(BABYLON.BaseTexture));
  63137. BABYLON.CubeTexture = CubeTexture;
  63138. })(BABYLON || (BABYLON = {}));
  63139. //# sourceMappingURL=babylon.cubeTexture.js.map
  63140. var BABYLON;
  63141. (function (BABYLON) {
  63142. var RenderTargetTexture = /** @class */ (function (_super) {
  63143. __extends(RenderTargetTexture, _super);
  63144. /**
  63145. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63146. * or used a shadow, depth texture...
  63147. * @param name The friendly name of the texture
  63148. * @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)
  63149. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63150. * @param generateMipMaps True if mip maps need to be generated after render.
  63151. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63152. * @param type The type of the buffer in the RTT (int, half float, float...)
  63153. * @param isCube True if a cube texture needs to be created
  63154. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63155. * @param generateDepthBuffer True to generate a depth buffer
  63156. * @param generateStencilBuffer True to generate a stencil buffer
  63157. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63158. */
  63159. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63160. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63161. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63162. if (isCube === void 0) { isCube = false; }
  63163. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63164. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63165. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63166. if (isMulti === void 0) { isMulti = false; }
  63167. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63168. _this.isCube = isCube;
  63169. /**
  63170. * Use this list to define the list of mesh you want to render.
  63171. */
  63172. _this.renderList = new Array();
  63173. _this.renderParticles = true;
  63174. _this.renderSprites = false;
  63175. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63176. _this.ignoreCameraViewport = false;
  63177. // Events
  63178. /**
  63179. * An event triggered when the texture is unbind.
  63180. */
  63181. _this.onBeforeBindObservable = new BABYLON.Observable();
  63182. /**
  63183. * An event triggered when the texture is unbind.
  63184. */
  63185. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63186. /**
  63187. * An event triggered before rendering the texture
  63188. */
  63189. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63190. /**
  63191. * An event triggered after rendering the texture
  63192. */
  63193. _this.onAfterRenderObservable = new BABYLON.Observable();
  63194. /**
  63195. * An event triggered after the texture clear
  63196. */
  63197. _this.onClearObservable = new BABYLON.Observable();
  63198. _this._currentRefreshId = -1;
  63199. _this._refreshRate = 1;
  63200. _this._samples = 1;
  63201. /**
  63202. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63203. * It must define where the camera used to render the texture is set
  63204. */
  63205. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63206. scene = _this.getScene();
  63207. if (!scene) {
  63208. return _this;
  63209. }
  63210. _this._engine = scene.getEngine();
  63211. _this.name = name;
  63212. _this.isRenderTarget = true;
  63213. _this._initialSizeParameter = size;
  63214. _this._processSizeParameter(size);
  63215. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63216. });
  63217. _this._generateMipMaps = generateMipMaps ? true : false;
  63218. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63219. // Rendering groups
  63220. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63221. if (isMulti) {
  63222. return _this;
  63223. }
  63224. _this._renderTargetOptions = {
  63225. generateMipMaps: generateMipMaps,
  63226. type: type,
  63227. samplingMode: samplingMode,
  63228. generateDepthBuffer: generateDepthBuffer,
  63229. generateStencilBuffer: generateStencilBuffer
  63230. };
  63231. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63232. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63233. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63234. }
  63235. if (isCube) {
  63236. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63237. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63238. _this._textureMatrix = BABYLON.Matrix.Identity();
  63239. }
  63240. else {
  63241. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63242. }
  63243. return _this;
  63244. }
  63245. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63246. get: function () {
  63247. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63248. },
  63249. enumerable: true,
  63250. configurable: true
  63251. });
  63252. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63253. get: function () {
  63254. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63255. },
  63256. enumerable: true,
  63257. configurable: true
  63258. });
  63259. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63260. get: function () {
  63261. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63262. },
  63263. enumerable: true,
  63264. configurable: true
  63265. });
  63266. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63267. set: function (callback) {
  63268. if (this._onAfterUnbindObserver) {
  63269. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63270. }
  63271. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63272. },
  63273. enumerable: true,
  63274. configurable: true
  63275. });
  63276. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63277. set: function (callback) {
  63278. if (this._onBeforeRenderObserver) {
  63279. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63280. }
  63281. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63282. },
  63283. enumerable: true,
  63284. configurable: true
  63285. });
  63286. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63287. set: function (callback) {
  63288. if (this._onAfterRenderObserver) {
  63289. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63290. }
  63291. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63292. },
  63293. enumerable: true,
  63294. configurable: true
  63295. });
  63296. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63297. set: function (callback) {
  63298. if (this._onClearObserver) {
  63299. this.onClearObservable.remove(this._onClearObserver);
  63300. }
  63301. this._onClearObserver = this.onClearObservable.add(callback);
  63302. },
  63303. enumerable: true,
  63304. configurable: true
  63305. });
  63306. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63307. get: function () {
  63308. return this._renderTargetOptions;
  63309. },
  63310. enumerable: true,
  63311. configurable: true
  63312. });
  63313. RenderTargetTexture.prototype._onRatioRescale = function () {
  63314. if (this._sizeRatio) {
  63315. this.resize(this._initialSizeParameter);
  63316. }
  63317. };
  63318. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63319. get: function () {
  63320. return this._boundingBoxSize;
  63321. },
  63322. /**
  63323. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63324. * When defined, the cubemap will switch to local mode
  63325. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63326. * @example https://www.babylonjs-playground.com/#RNASML
  63327. */
  63328. set: function (value) {
  63329. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63330. return;
  63331. }
  63332. this._boundingBoxSize = value;
  63333. var scene = this.getScene();
  63334. if (scene) {
  63335. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63336. }
  63337. },
  63338. enumerable: true,
  63339. configurable: true
  63340. });
  63341. /**
  63342. * Creates a depth stencil texture.
  63343. * This is only available in WebGL 2 or with the depth texture extension available.
  63344. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63345. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63346. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63347. */
  63348. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63349. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63350. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63351. if (generateStencil === void 0) { generateStencil = false; }
  63352. if (!this.getScene()) {
  63353. return;
  63354. }
  63355. var engine = this.getScene().getEngine();
  63356. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63357. bilinearFiltering: bilinearFiltering,
  63358. comparisonFunction: comparisonFunction,
  63359. generateStencil: generateStencil,
  63360. isCube: this.isCube
  63361. });
  63362. engine.setFrameBufferDepthStencilTexture(this);
  63363. };
  63364. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63365. if (size.ratio) {
  63366. this._sizeRatio = size.ratio;
  63367. this._size = {
  63368. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63369. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63370. };
  63371. }
  63372. else {
  63373. this._size = size;
  63374. }
  63375. };
  63376. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63377. get: function () {
  63378. return this._samples;
  63379. },
  63380. set: function (value) {
  63381. if (this._samples === value) {
  63382. return;
  63383. }
  63384. var scene = this.getScene();
  63385. if (!scene) {
  63386. return;
  63387. }
  63388. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63389. },
  63390. enumerable: true,
  63391. configurable: true
  63392. });
  63393. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63394. this._currentRefreshId = -1;
  63395. };
  63396. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63397. get: function () {
  63398. return this._refreshRate;
  63399. },
  63400. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63401. set: function (value) {
  63402. this._refreshRate = value;
  63403. this.resetRefreshCounter();
  63404. },
  63405. enumerable: true,
  63406. configurable: true
  63407. });
  63408. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63409. if (!this._postProcessManager) {
  63410. var scene = this.getScene();
  63411. if (!scene) {
  63412. return;
  63413. }
  63414. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63415. this._postProcesses = new Array();
  63416. }
  63417. this._postProcesses.push(postProcess);
  63418. this._postProcesses[0].autoClear = false;
  63419. };
  63420. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63421. if (!this._postProcesses) {
  63422. return;
  63423. }
  63424. if (dispose) {
  63425. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63426. var postProcess = _a[_i];
  63427. postProcess.dispose();
  63428. }
  63429. }
  63430. this._postProcesses = [];
  63431. };
  63432. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63433. if (!this._postProcesses) {
  63434. return;
  63435. }
  63436. var index = this._postProcesses.indexOf(postProcess);
  63437. if (index === -1) {
  63438. return;
  63439. }
  63440. this._postProcesses.splice(index, 1);
  63441. if (this._postProcesses.length > 0) {
  63442. this._postProcesses[0].autoClear = false;
  63443. }
  63444. };
  63445. RenderTargetTexture.prototype._shouldRender = function () {
  63446. if (this._currentRefreshId === -1) { // At least render once
  63447. this._currentRefreshId = 1;
  63448. return true;
  63449. }
  63450. if (this.refreshRate === this._currentRefreshId) {
  63451. this._currentRefreshId = 1;
  63452. return true;
  63453. }
  63454. this._currentRefreshId++;
  63455. return false;
  63456. };
  63457. RenderTargetTexture.prototype.getRenderSize = function () {
  63458. if (this._size.width) {
  63459. return this._size.width;
  63460. }
  63461. return this._size;
  63462. };
  63463. RenderTargetTexture.prototype.getRenderWidth = function () {
  63464. if (this._size.width) {
  63465. return this._size.width;
  63466. }
  63467. return this._size;
  63468. };
  63469. RenderTargetTexture.prototype.getRenderHeight = function () {
  63470. if (this._size.width) {
  63471. return this._size.height;
  63472. }
  63473. return this._size;
  63474. };
  63475. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63476. get: function () {
  63477. return true;
  63478. },
  63479. enumerable: true,
  63480. configurable: true
  63481. });
  63482. RenderTargetTexture.prototype.scale = function (ratio) {
  63483. var newSize = this.getRenderSize() * ratio;
  63484. this.resize(newSize);
  63485. };
  63486. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63487. if (this.isCube) {
  63488. return this._textureMatrix;
  63489. }
  63490. return _super.prototype.getReflectionTextureMatrix.call(this);
  63491. };
  63492. RenderTargetTexture.prototype.resize = function (size) {
  63493. this.releaseInternalTexture();
  63494. var scene = this.getScene();
  63495. if (!scene) {
  63496. return;
  63497. }
  63498. this._processSizeParameter(size);
  63499. if (this.isCube) {
  63500. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63501. }
  63502. else {
  63503. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63504. }
  63505. };
  63506. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63507. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63508. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63509. var scene = this.getScene();
  63510. if (!scene) {
  63511. return;
  63512. }
  63513. var engine = scene.getEngine();
  63514. if (this.useCameraPostProcesses !== undefined) {
  63515. useCameraPostProcess = this.useCameraPostProcesses;
  63516. }
  63517. if (this._waitingRenderList) {
  63518. this.renderList = [];
  63519. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63520. var id = this._waitingRenderList[index];
  63521. var mesh_1 = scene.getMeshByID(id);
  63522. if (mesh_1) {
  63523. this.renderList.push(mesh_1);
  63524. }
  63525. }
  63526. delete this._waitingRenderList;
  63527. }
  63528. // Is predicate defined?
  63529. if (this.renderListPredicate) {
  63530. if (this.renderList) {
  63531. this.renderList.splice(0); // Clear previous renderList
  63532. }
  63533. else {
  63534. this.renderList = [];
  63535. }
  63536. var scene = this.getScene();
  63537. if (!scene) {
  63538. return;
  63539. }
  63540. var sceneMeshes = scene.meshes;
  63541. for (var index = 0; index < sceneMeshes.length; index++) {
  63542. var mesh = sceneMeshes[index];
  63543. if (this.renderListPredicate(mesh)) {
  63544. this.renderList.push(mesh);
  63545. }
  63546. }
  63547. }
  63548. this.onBeforeBindObservable.notifyObservers(this);
  63549. // Set custom projection.
  63550. // Needs to be before binding to prevent changing the aspect ratio.
  63551. var camera;
  63552. if (this.activeCamera) {
  63553. camera = this.activeCamera;
  63554. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63555. if (this.activeCamera !== scene.activeCamera) {
  63556. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63557. }
  63558. }
  63559. else {
  63560. camera = scene.activeCamera;
  63561. if (camera) {
  63562. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63563. }
  63564. }
  63565. // Prepare renderingManager
  63566. this._renderingManager.reset();
  63567. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63568. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63569. var sceneRenderId = scene.getRenderId();
  63570. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63571. var mesh = currentRenderList[meshIndex];
  63572. if (mesh) {
  63573. if (!mesh.isReady(this.refreshRate === 0)) {
  63574. this.resetRefreshCounter();
  63575. continue;
  63576. }
  63577. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63578. var isMasked = void 0;
  63579. if (!this.renderList && camera) {
  63580. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63581. }
  63582. else {
  63583. isMasked = false;
  63584. }
  63585. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63586. mesh._activate(sceneRenderId);
  63587. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63588. var subMesh = mesh.subMeshes[subIndex];
  63589. scene._activeIndices.addCount(subMesh.indexCount, false);
  63590. this._renderingManager.dispatch(subMesh, mesh);
  63591. }
  63592. }
  63593. }
  63594. }
  63595. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63596. var particleSystem = scene.particleSystems[particleIndex];
  63597. var emitter = particleSystem.emitter;
  63598. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63599. continue;
  63600. }
  63601. if (currentRenderList.indexOf(emitter) >= 0) {
  63602. this._renderingManager.dispatchParticles(particleSystem);
  63603. }
  63604. }
  63605. if (this.isCube) {
  63606. for (var face = 0; face < 6; face++) {
  63607. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63608. scene.incrementRenderId();
  63609. scene.resetCachedMaterial();
  63610. }
  63611. }
  63612. else {
  63613. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63614. }
  63615. this.onAfterUnbindObservable.notifyObservers(this);
  63616. if (scene.activeCamera) {
  63617. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63618. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63619. }
  63620. engine.setViewport(scene.activeCamera.viewport);
  63621. }
  63622. scene.resetCachedMaterial();
  63623. };
  63624. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63625. var minimum = 128;
  63626. var x = renderDimension * scale;
  63627. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63628. // Ensure we don't exceed the render dimension (while staying POT)
  63629. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63630. };
  63631. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63632. var _this = this;
  63633. if (!this._texture) {
  63634. return;
  63635. }
  63636. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63637. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63638. });
  63639. };
  63640. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63641. var scene = this.getScene();
  63642. if (!scene) {
  63643. return;
  63644. }
  63645. var engine = scene.getEngine();
  63646. if (!this._texture) {
  63647. return;
  63648. }
  63649. // Bind
  63650. if (this._postProcessManager) {
  63651. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63652. }
  63653. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63654. if (this._texture) {
  63655. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63656. }
  63657. }
  63658. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63659. // Clear
  63660. if (this.onClearObservable.hasObservers()) {
  63661. this.onClearObservable.notifyObservers(engine);
  63662. }
  63663. else {
  63664. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63665. }
  63666. if (!this._doNotChangeAspectRatio) {
  63667. scene.updateTransformMatrix(true);
  63668. }
  63669. // Render
  63670. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63671. if (this._postProcessManager) {
  63672. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63673. }
  63674. else if (useCameraPostProcess) {
  63675. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63676. }
  63677. if (!this._doNotChangeAspectRatio) {
  63678. scene.updateTransformMatrix(true);
  63679. }
  63680. // Dump ?
  63681. if (dumpForDebug) {
  63682. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63683. }
  63684. // Unbind
  63685. if (!this.isCube || faceIndex === 5) {
  63686. if (this.isCube) {
  63687. if (faceIndex === 5) {
  63688. engine.generateMipMapsForCubemap(this._texture);
  63689. }
  63690. }
  63691. this.unbindFrameBuffer(engine, faceIndex);
  63692. }
  63693. else {
  63694. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63695. }
  63696. };
  63697. /**
  63698. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63699. * This allowed control for front to back rendering or reversly depending of the special needs.
  63700. *
  63701. * @param renderingGroupId The rendering group id corresponding to its index
  63702. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63703. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63704. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63705. */
  63706. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63707. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63708. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63709. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63710. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63711. };
  63712. /**
  63713. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63714. *
  63715. * @param renderingGroupId The rendering group id corresponding to its index
  63716. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63717. */
  63718. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63719. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63720. };
  63721. RenderTargetTexture.prototype.clone = function () {
  63722. var textureSize = this.getSize();
  63723. 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);
  63724. // Base texture
  63725. newTexture.hasAlpha = this.hasAlpha;
  63726. newTexture.level = this.level;
  63727. // RenderTarget Texture
  63728. newTexture.coordinatesMode = this.coordinatesMode;
  63729. if (this.renderList) {
  63730. newTexture.renderList = this.renderList.slice(0);
  63731. }
  63732. return newTexture;
  63733. };
  63734. RenderTargetTexture.prototype.serialize = function () {
  63735. if (!this.name) {
  63736. return null;
  63737. }
  63738. var serializationObject = _super.prototype.serialize.call(this);
  63739. serializationObject.renderTargetSize = this.getRenderSize();
  63740. serializationObject.renderList = [];
  63741. if (this.renderList) {
  63742. for (var index = 0; index < this.renderList.length; index++) {
  63743. serializationObject.renderList.push(this.renderList[index].id);
  63744. }
  63745. }
  63746. return serializationObject;
  63747. };
  63748. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63749. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63750. var objBuffer = this.getInternalTexture();
  63751. var scene = this.getScene();
  63752. if (objBuffer && scene) {
  63753. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63754. }
  63755. };
  63756. RenderTargetTexture.prototype.dispose = function () {
  63757. if (this._postProcessManager) {
  63758. this._postProcessManager.dispose();
  63759. this._postProcessManager = null;
  63760. }
  63761. this.clearPostProcesses(true);
  63762. if (this._resizeObserver) {
  63763. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63764. this._resizeObserver = null;
  63765. }
  63766. this.renderList = null;
  63767. // Remove from custom render targets
  63768. var scene = this.getScene();
  63769. if (!scene) {
  63770. return;
  63771. }
  63772. var index = scene.customRenderTargets.indexOf(this);
  63773. if (index >= 0) {
  63774. scene.customRenderTargets.splice(index, 1);
  63775. }
  63776. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63777. var camera = _a[_i];
  63778. index = camera.customRenderTargets.indexOf(this);
  63779. if (index >= 0) {
  63780. camera.customRenderTargets.splice(index, 1);
  63781. }
  63782. }
  63783. _super.prototype.dispose.call(this);
  63784. };
  63785. RenderTargetTexture.prototype._rebuild = function () {
  63786. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63787. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63788. }
  63789. if (this._postProcessManager) {
  63790. this._postProcessManager._rebuild();
  63791. }
  63792. };
  63793. /**
  63794. * Clear the info related to rendering groups preventing retention point in material dispose.
  63795. */
  63796. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63797. if (this._renderingManager) {
  63798. this._renderingManager.freeRenderingGroups();
  63799. }
  63800. };
  63801. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63802. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63803. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63804. return RenderTargetTexture;
  63805. }(BABYLON.Texture));
  63806. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63807. })(BABYLON || (BABYLON = {}));
  63808. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63809. var BABYLON;
  63810. (function (BABYLON) {
  63811. ;
  63812. var MultiRenderTarget = /** @class */ (function (_super) {
  63813. __extends(MultiRenderTarget, _super);
  63814. function MultiRenderTarget(name, size, count, scene, options) {
  63815. var _this = this;
  63816. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63817. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63818. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63819. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63820. _this._engine = scene.getEngine();
  63821. if (!_this.isSupported) {
  63822. _this.dispose();
  63823. return;
  63824. }
  63825. var types = [];
  63826. var samplingModes = [];
  63827. for (var i = 0; i < count; i++) {
  63828. if (options && options.types && options.types[i] !== undefined) {
  63829. types.push(options.types[i]);
  63830. }
  63831. else {
  63832. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63833. }
  63834. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63835. samplingModes.push(options.samplingModes[i]);
  63836. }
  63837. else {
  63838. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63839. }
  63840. }
  63841. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63842. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63843. _this._size = size;
  63844. _this._multiRenderTargetOptions = {
  63845. samplingModes: samplingModes,
  63846. generateMipMaps: generateMipMaps,
  63847. generateDepthBuffer: generateDepthBuffer,
  63848. generateStencilBuffer: generateStencilBuffer,
  63849. generateDepthTexture: generateDepthTexture,
  63850. types: types,
  63851. textureCount: count
  63852. };
  63853. _this._createInternalTextures();
  63854. _this._createTextures();
  63855. return _this;
  63856. }
  63857. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63858. get: function () {
  63859. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63860. },
  63861. enumerable: true,
  63862. configurable: true
  63863. });
  63864. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63865. get: function () {
  63866. return this._textures;
  63867. },
  63868. enumerable: true,
  63869. configurable: true
  63870. });
  63871. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63872. get: function () {
  63873. return this._textures[this._textures.length - 1];
  63874. },
  63875. enumerable: true,
  63876. configurable: true
  63877. });
  63878. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63879. set: function (wrap) {
  63880. if (this._textures) {
  63881. for (var i = 0; i < this._textures.length; i++) {
  63882. this._textures[i].wrapU = wrap;
  63883. }
  63884. }
  63885. },
  63886. enumerable: true,
  63887. configurable: true
  63888. });
  63889. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63890. set: function (wrap) {
  63891. if (this._textures) {
  63892. for (var i = 0; i < this._textures.length; i++) {
  63893. this._textures[i].wrapV = wrap;
  63894. }
  63895. }
  63896. },
  63897. enumerable: true,
  63898. configurable: true
  63899. });
  63900. MultiRenderTarget.prototype._rebuild = function () {
  63901. this.releaseInternalTextures();
  63902. this._createInternalTextures();
  63903. for (var i = 0; i < this._internalTextures.length; i++) {
  63904. var texture = this._textures[i];
  63905. texture._texture = this._internalTextures[i];
  63906. }
  63907. // Keeps references to frame buffer and stencil/depth buffer
  63908. this._texture = this._internalTextures[0];
  63909. };
  63910. MultiRenderTarget.prototype._createInternalTextures = function () {
  63911. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63912. };
  63913. MultiRenderTarget.prototype._createTextures = function () {
  63914. this._textures = [];
  63915. for (var i = 0; i < this._internalTextures.length; i++) {
  63916. var texture = new BABYLON.Texture(null, this.getScene());
  63917. texture._texture = this._internalTextures[i];
  63918. this._textures.push(texture);
  63919. }
  63920. // Keeps references to frame buffer and stencil/depth buffer
  63921. this._texture = this._internalTextures[0];
  63922. };
  63923. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63924. get: function () {
  63925. return this._samples;
  63926. },
  63927. set: function (value) {
  63928. if (this._samples === value) {
  63929. return;
  63930. }
  63931. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63932. },
  63933. enumerable: true,
  63934. configurable: true
  63935. });
  63936. MultiRenderTarget.prototype.resize = function (size) {
  63937. this.releaseInternalTextures();
  63938. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63939. this._createInternalTextures();
  63940. };
  63941. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63942. var _this = this;
  63943. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63944. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63945. });
  63946. };
  63947. MultiRenderTarget.prototype.dispose = function () {
  63948. this.releaseInternalTextures();
  63949. _super.prototype.dispose.call(this);
  63950. };
  63951. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63952. if (!this._internalTextures) {
  63953. return;
  63954. }
  63955. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63956. if (this._internalTextures[i] !== undefined) {
  63957. this._internalTextures[i].dispose();
  63958. this._internalTextures.splice(i, 1);
  63959. }
  63960. }
  63961. };
  63962. return MultiRenderTarget;
  63963. }(BABYLON.RenderTargetTexture));
  63964. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63965. })(BABYLON || (BABYLON = {}));
  63966. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63967. var BABYLON;
  63968. (function (BABYLON) {
  63969. var MirrorTexture = /** @class */ (function (_super) {
  63970. __extends(MirrorTexture, _super);
  63971. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63972. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63973. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63974. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63975. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63976. _this.scene = scene;
  63977. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63978. _this._transformMatrix = BABYLON.Matrix.Zero();
  63979. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63980. _this._adaptiveBlurKernel = 0;
  63981. _this._blurKernelX = 0;
  63982. _this._blurKernelY = 0;
  63983. _this._blurRatio = 1.0;
  63984. _this.ignoreCameraViewport = true;
  63985. _this._updateGammaSpace();
  63986. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63987. _this._updateGammaSpace;
  63988. });
  63989. _this.onBeforeRenderObservable.add(function () {
  63990. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63991. _this._savedViewMatrix = scene.getViewMatrix();
  63992. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63993. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63994. scene.clipPlane = _this.mirrorPlane;
  63995. scene.getEngine().cullBackFaces = false;
  63996. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63997. });
  63998. _this.onAfterRenderObservable.add(function () {
  63999. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64000. scene.getEngine().cullBackFaces = true;
  64001. scene._mirroredCameraPosition = null;
  64002. delete scene.clipPlane;
  64003. });
  64004. return _this;
  64005. }
  64006. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64007. get: function () {
  64008. return this._blurRatio;
  64009. },
  64010. set: function (value) {
  64011. if (this._blurRatio === value) {
  64012. return;
  64013. }
  64014. this._blurRatio = value;
  64015. this._preparePostProcesses();
  64016. },
  64017. enumerable: true,
  64018. configurable: true
  64019. });
  64020. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64021. set: function (value) {
  64022. this._adaptiveBlurKernel = value;
  64023. this._autoComputeBlurKernel();
  64024. },
  64025. enumerable: true,
  64026. configurable: true
  64027. });
  64028. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64029. set: function (value) {
  64030. this.blurKernelX = value;
  64031. this.blurKernelY = value;
  64032. },
  64033. enumerable: true,
  64034. configurable: true
  64035. });
  64036. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64037. get: function () {
  64038. return this._blurKernelX;
  64039. },
  64040. set: function (value) {
  64041. if (this._blurKernelX === value) {
  64042. return;
  64043. }
  64044. this._blurKernelX = value;
  64045. this._preparePostProcesses();
  64046. },
  64047. enumerable: true,
  64048. configurable: true
  64049. });
  64050. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64051. get: function () {
  64052. return this._blurKernelY;
  64053. },
  64054. set: function (value) {
  64055. if (this._blurKernelY === value) {
  64056. return;
  64057. }
  64058. this._blurKernelY = value;
  64059. this._preparePostProcesses();
  64060. },
  64061. enumerable: true,
  64062. configurable: true
  64063. });
  64064. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64065. var engine = this.getScene().getEngine();
  64066. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64067. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64068. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64069. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64070. };
  64071. MirrorTexture.prototype._onRatioRescale = function () {
  64072. if (this._sizeRatio) {
  64073. this.resize(this._initialSizeParameter);
  64074. if (!this._adaptiveBlurKernel) {
  64075. this._preparePostProcesses();
  64076. }
  64077. }
  64078. if (this._adaptiveBlurKernel) {
  64079. this._autoComputeBlurKernel();
  64080. }
  64081. };
  64082. MirrorTexture.prototype._updateGammaSpace = function () {
  64083. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64084. };
  64085. MirrorTexture.prototype._preparePostProcesses = function () {
  64086. this.clearPostProcesses(true);
  64087. if (this._blurKernelX && this._blurKernelY) {
  64088. var engine = this.getScene().getEngine();
  64089. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64090. 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);
  64091. this._blurX.autoClear = false;
  64092. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64093. this._blurX.inputTexture = this._texture;
  64094. }
  64095. else {
  64096. this._blurX.alwaysForcePOT = true;
  64097. }
  64098. 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);
  64099. this._blurY.autoClear = false;
  64100. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64101. this.addPostProcess(this._blurX);
  64102. this.addPostProcess(this._blurY);
  64103. }
  64104. else {
  64105. if (this._blurY) {
  64106. this.removePostProcess(this._blurY);
  64107. this._blurY.dispose();
  64108. this._blurY = null;
  64109. }
  64110. if (this._blurX) {
  64111. this.removePostProcess(this._blurX);
  64112. this._blurX.dispose();
  64113. this._blurX = null;
  64114. }
  64115. }
  64116. };
  64117. MirrorTexture.prototype.clone = function () {
  64118. var scene = this.getScene();
  64119. if (!scene) {
  64120. return this;
  64121. }
  64122. var textureSize = this.getSize();
  64123. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64124. // Base texture
  64125. newTexture.hasAlpha = this.hasAlpha;
  64126. newTexture.level = this.level;
  64127. // Mirror Texture
  64128. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64129. if (this.renderList) {
  64130. newTexture.renderList = this.renderList.slice(0);
  64131. }
  64132. return newTexture;
  64133. };
  64134. MirrorTexture.prototype.serialize = function () {
  64135. if (!this.name) {
  64136. return null;
  64137. }
  64138. var serializationObject = _super.prototype.serialize.call(this);
  64139. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64140. return serializationObject;
  64141. };
  64142. MirrorTexture.prototype.dispose = function () {
  64143. _super.prototype.dispose.call(this);
  64144. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64145. };
  64146. return MirrorTexture;
  64147. }(BABYLON.RenderTargetTexture));
  64148. BABYLON.MirrorTexture = MirrorTexture;
  64149. })(BABYLON || (BABYLON = {}));
  64150. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64151. var BABYLON;
  64152. (function (BABYLON) {
  64153. /**
  64154. * Creates a refraction texture used by refraction channel of the standard material.
  64155. * @param name the texture name
  64156. * @param size size of the underlying texture
  64157. * @param scene root scene
  64158. */
  64159. var RefractionTexture = /** @class */ (function (_super) {
  64160. __extends(RefractionTexture, _super);
  64161. function RefractionTexture(name, size, scene, generateMipMaps) {
  64162. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64163. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64164. _this.depth = 2.0;
  64165. _this.onBeforeRenderObservable.add(function () {
  64166. scene.clipPlane = _this.refractionPlane;
  64167. });
  64168. _this.onAfterRenderObservable.add(function () {
  64169. delete scene.clipPlane;
  64170. });
  64171. return _this;
  64172. }
  64173. RefractionTexture.prototype.clone = function () {
  64174. var scene = this.getScene();
  64175. if (!scene) {
  64176. return this;
  64177. }
  64178. var textureSize = this.getSize();
  64179. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64180. // Base texture
  64181. newTexture.hasAlpha = this.hasAlpha;
  64182. newTexture.level = this.level;
  64183. // Refraction Texture
  64184. newTexture.refractionPlane = this.refractionPlane.clone();
  64185. if (this.renderList) {
  64186. newTexture.renderList = this.renderList.slice(0);
  64187. }
  64188. newTexture.depth = this.depth;
  64189. return newTexture;
  64190. };
  64191. RefractionTexture.prototype.serialize = function () {
  64192. if (!this.name) {
  64193. return null;
  64194. }
  64195. var serializationObject = _super.prototype.serialize.call(this);
  64196. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64197. serializationObject.depth = this.depth;
  64198. return serializationObject;
  64199. };
  64200. return RefractionTexture;
  64201. }(BABYLON.RenderTargetTexture));
  64202. BABYLON.RefractionTexture = RefractionTexture;
  64203. })(BABYLON || (BABYLON = {}));
  64204. //# sourceMappingURL=babylon.refractionTexture.js.map
  64205. var BABYLON;
  64206. (function (BABYLON) {
  64207. /**
  64208. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64209. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64210. */
  64211. var DynamicTexture = /** @class */ (function (_super) {
  64212. __extends(DynamicTexture, _super);
  64213. /**
  64214. * Creates a {BABYLON.DynamicTexture}
  64215. * @param name defines the name of the texture
  64216. * @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
  64217. * @param scene defines the scene where you want the texture
  64218. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64219. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64220. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64221. */
  64222. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64223. if (scene === void 0) { scene = null; }
  64224. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64225. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64226. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64227. _this.name = name;
  64228. _this._engine = _this.getScene().getEngine();
  64229. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64230. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64231. _this._generateMipMaps = generateMipMaps;
  64232. if (options.getContext) {
  64233. _this._canvas = options;
  64234. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64235. }
  64236. else {
  64237. _this._canvas = document.createElement("canvas");
  64238. if (options.width || options.width === 0) {
  64239. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64240. }
  64241. else {
  64242. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64243. }
  64244. }
  64245. var textureSize = _this.getSize();
  64246. _this._canvas.width = textureSize.width;
  64247. _this._canvas.height = textureSize.height;
  64248. _this._context = _this._canvas.getContext("2d");
  64249. return _this;
  64250. }
  64251. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64252. /**
  64253. * Gets the current state of canRescale
  64254. */
  64255. get: function () {
  64256. return true;
  64257. },
  64258. enumerable: true,
  64259. configurable: true
  64260. });
  64261. DynamicTexture.prototype._recreate = function (textureSize) {
  64262. this._canvas.width = textureSize.width;
  64263. this._canvas.height = textureSize.height;
  64264. this.releaseInternalTexture();
  64265. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64266. };
  64267. /**
  64268. * Scales the texture
  64269. * @param ratio the scale factor to apply to both width and height
  64270. */
  64271. DynamicTexture.prototype.scale = function (ratio) {
  64272. var textureSize = this.getSize();
  64273. textureSize.width *= ratio;
  64274. textureSize.height *= ratio;
  64275. this._recreate(textureSize);
  64276. };
  64277. /**
  64278. * Resizes the texture
  64279. * @param width the new width
  64280. * @param height the new height
  64281. */
  64282. DynamicTexture.prototype.scaleTo = function (width, height) {
  64283. var textureSize = this.getSize();
  64284. textureSize.width = width;
  64285. textureSize.height = height;
  64286. this._recreate(textureSize);
  64287. };
  64288. /**
  64289. * Gets the context of the canvas used by the texture
  64290. * @returns the canvas context of the dynamic texture
  64291. */
  64292. DynamicTexture.prototype.getContext = function () {
  64293. return this._context;
  64294. };
  64295. /**
  64296. * Clears the texture
  64297. */
  64298. DynamicTexture.prototype.clear = function () {
  64299. var size = this.getSize();
  64300. this._context.fillRect(0, 0, size.width, size.height);
  64301. };
  64302. /**
  64303. * Updates the texture
  64304. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64305. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64306. */
  64307. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64308. if (premulAlpha === void 0) { premulAlpha = false; }
  64309. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64310. };
  64311. /**
  64312. * Draws text onto the texture
  64313. * @param text defines the text to be drawn
  64314. * @param x defines the placement of the text from the left
  64315. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64316. * @param font defines the font to be used with font-style, font-size, font-name
  64317. * @param color defines the color used for the text
  64318. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64319. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64320. * @param update defines whether texture is immediately update (default is true)
  64321. */
  64322. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64323. if (update === void 0) { update = true; }
  64324. var size = this.getSize();
  64325. if (clearColor) {
  64326. this._context.fillStyle = clearColor;
  64327. this._context.fillRect(0, 0, size.width, size.height);
  64328. }
  64329. this._context.font = font;
  64330. if (x === null || x === undefined) {
  64331. var textSize = this._context.measureText(text);
  64332. x = (size.width - textSize.width) / 2;
  64333. }
  64334. if (y === null || y === undefined) {
  64335. var fontSize = parseInt((font.replace(/\D/g, '')));
  64336. y = (size.height / 2) + (fontSize / 3.65);
  64337. }
  64338. this._context.fillStyle = color;
  64339. this._context.fillText(text, x, y);
  64340. if (update) {
  64341. this.update(invertY);
  64342. }
  64343. };
  64344. /**
  64345. * Clones the texture
  64346. * @returns the clone of the texture.
  64347. */
  64348. DynamicTexture.prototype.clone = function () {
  64349. var scene = this.getScene();
  64350. if (!scene) {
  64351. return this;
  64352. }
  64353. var textureSize = this.getSize();
  64354. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64355. // Base texture
  64356. newTexture.hasAlpha = this.hasAlpha;
  64357. newTexture.level = this.level;
  64358. // Dynamic Texture
  64359. newTexture.wrapU = this.wrapU;
  64360. newTexture.wrapV = this.wrapV;
  64361. return newTexture;
  64362. };
  64363. /** @hidden */
  64364. DynamicTexture.prototype._rebuild = function () {
  64365. this.update();
  64366. };
  64367. return DynamicTexture;
  64368. }(BABYLON.Texture));
  64369. BABYLON.DynamicTexture = DynamicTexture;
  64370. })(BABYLON || (BABYLON = {}));
  64371. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64372. var BABYLON;
  64373. (function (BABYLON) {
  64374. var VideoTexture = /** @class */ (function (_super) {
  64375. __extends(VideoTexture, _super);
  64376. /**
  64377. * Creates a video texture.
  64378. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64379. * @param {string | null} name optional name, will detect from video source, if not defined
  64380. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64381. * @param {BABYLON.Scene} scene is obviously the current scene.
  64382. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64383. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64384. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64385. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64386. */
  64387. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64388. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64389. if (invertY === void 0) { invertY = false; }
  64390. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64391. if (settings === void 0) { settings = {
  64392. autoPlay: true,
  64393. loop: true,
  64394. autoUpdateTexture: true,
  64395. }; }
  64396. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64397. _this._onUserActionRequestedObservable = null;
  64398. _this._stillImageCaptured = false;
  64399. _this._createInternalTexture = function () {
  64400. if (_this._texture != null) {
  64401. return;
  64402. }
  64403. if (!_this._engine.needPOTTextures ||
  64404. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64405. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64406. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64407. }
  64408. else {
  64409. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64410. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64411. _this._generateMipMaps = false;
  64412. }
  64413. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64414. if (!_this.video.autoplay) {
  64415. var oldHandler_1 = _this.video.onplaying;
  64416. var error_1 = false;
  64417. _this.video.onplaying = function () {
  64418. _this.video.onplaying = oldHandler_1;
  64419. _this._texture.isReady = true;
  64420. _this._updateInternalTexture();
  64421. if (!error_1) {
  64422. _this.video.pause();
  64423. }
  64424. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64425. _this.onLoadObservable.notifyObservers(_this);
  64426. }
  64427. };
  64428. var playing = _this.video.play();
  64429. if (playing) {
  64430. playing.then(function () {
  64431. // Everything is good.
  64432. })
  64433. .catch(function () {
  64434. error_1 = true;
  64435. // On Chrome for instance, new policies might prevent playing without user interaction.
  64436. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64437. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64438. }
  64439. });
  64440. }
  64441. else {
  64442. _this.video.onplaying = oldHandler_1;
  64443. _this._texture.isReady = true;
  64444. _this._updateInternalTexture();
  64445. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64446. _this.onLoadObservable.notifyObservers(_this);
  64447. }
  64448. }
  64449. }
  64450. else {
  64451. _this._texture.isReady = true;
  64452. _this._updateInternalTexture();
  64453. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64454. _this.onLoadObservable.notifyObservers(_this);
  64455. }
  64456. }
  64457. };
  64458. _this.reset = function () {
  64459. if (_this._texture == null) {
  64460. return;
  64461. }
  64462. _this._texture.dispose();
  64463. _this._texture = null;
  64464. };
  64465. _this._updateInternalTexture = function (e) {
  64466. if (_this._texture == null || !_this._texture.isReady) {
  64467. return;
  64468. }
  64469. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64470. return;
  64471. }
  64472. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64473. };
  64474. _this._engine = _this.getScene().getEngine();
  64475. _this._generateMipMaps = generateMipMaps;
  64476. _this._samplingMode = samplingMode;
  64477. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64478. _this.name = name || _this._getName(src);
  64479. _this.video = _this._getVideo(src);
  64480. if (settings.poster) {
  64481. _this.video.poster = settings.poster;
  64482. }
  64483. if (settings.autoPlay !== undefined) {
  64484. _this.video.autoplay = settings.autoPlay;
  64485. }
  64486. if (settings.loop !== undefined) {
  64487. _this.video.loop = settings.loop;
  64488. }
  64489. _this.video.setAttribute("playsinline", "");
  64490. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64491. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64492. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64493. _this.video.addEventListener("emptied", _this.reset);
  64494. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64495. _this._createInternalTexture();
  64496. }
  64497. return _this;
  64498. }
  64499. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64500. get: function () {
  64501. if (!this._onUserActionRequestedObservable) {
  64502. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64503. }
  64504. return this._onUserActionRequestedObservable;
  64505. },
  64506. enumerable: true,
  64507. configurable: true
  64508. });
  64509. VideoTexture.prototype._getName = function (src) {
  64510. if (src instanceof HTMLVideoElement) {
  64511. return src.currentSrc;
  64512. }
  64513. if (typeof src === "object") {
  64514. return src.toString();
  64515. }
  64516. return src;
  64517. };
  64518. ;
  64519. VideoTexture.prototype._getVideo = function (src) {
  64520. if (src instanceof HTMLVideoElement) {
  64521. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64522. return src;
  64523. }
  64524. var video = document.createElement("video");
  64525. if (typeof src === "string") {
  64526. BABYLON.Tools.SetCorsBehavior(src, video);
  64527. video.src = src;
  64528. }
  64529. else {
  64530. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64531. src.forEach(function (url) {
  64532. var source = document.createElement("source");
  64533. source.src = url;
  64534. video.appendChild(source);
  64535. });
  64536. }
  64537. return video;
  64538. };
  64539. ;
  64540. /**
  64541. * Internal method to initiate `update`.
  64542. */
  64543. VideoTexture.prototype._rebuild = function () {
  64544. this.update();
  64545. };
  64546. /**
  64547. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64548. */
  64549. VideoTexture.prototype.update = function () {
  64550. if (!this.autoUpdateTexture) {
  64551. // Expecting user to call `updateTexture` manually
  64552. return;
  64553. }
  64554. this.updateTexture(true);
  64555. };
  64556. /**
  64557. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64558. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64559. */
  64560. VideoTexture.prototype.updateTexture = function (isVisible) {
  64561. if (!isVisible) {
  64562. return;
  64563. }
  64564. if (this.video.paused && this._stillImageCaptured) {
  64565. return;
  64566. }
  64567. this._stillImageCaptured = true;
  64568. this._updateInternalTexture();
  64569. };
  64570. /**
  64571. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64572. * @param url New url.
  64573. */
  64574. VideoTexture.prototype.updateURL = function (url) {
  64575. this.video.src = url;
  64576. };
  64577. VideoTexture.prototype.dispose = function () {
  64578. _super.prototype.dispose.call(this);
  64579. if (this._onUserActionRequestedObservable) {
  64580. this._onUserActionRequestedObservable.clear();
  64581. this._onUserActionRequestedObservable = null;
  64582. }
  64583. this.video.removeEventListener("canplay", this._createInternalTexture);
  64584. this.video.removeEventListener("paused", this._updateInternalTexture);
  64585. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64586. this.video.removeEventListener("emptied", this.reset);
  64587. this.video.pause();
  64588. };
  64589. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64590. var video = document.createElement("video");
  64591. var constraintsDeviceId;
  64592. if (constraints && constraints.deviceId) {
  64593. constraintsDeviceId = {
  64594. exact: constraints.deviceId,
  64595. };
  64596. }
  64597. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64598. if (navigator.mediaDevices) {
  64599. navigator.mediaDevices.getUserMedia({ video: constraints })
  64600. .then(function (stream) {
  64601. if (video.mozSrcObject !== undefined) {
  64602. // hack for Firefox < 19
  64603. video.mozSrcObject = stream;
  64604. }
  64605. else {
  64606. video.srcObject = stream;
  64607. }
  64608. var onPlaying = function () {
  64609. if (onReady) {
  64610. onReady(new VideoTexture("video", video, scene, true, true));
  64611. }
  64612. video.removeEventListener("playing", onPlaying);
  64613. };
  64614. video.addEventListener("playing", onPlaying);
  64615. video.play();
  64616. })
  64617. .catch(function (err) {
  64618. BABYLON.Tools.Error(err.name);
  64619. });
  64620. }
  64621. else {
  64622. navigator.getUserMedia =
  64623. navigator.getUserMedia ||
  64624. navigator.webkitGetUserMedia ||
  64625. navigator.mozGetUserMedia ||
  64626. navigator.msGetUserMedia;
  64627. if (navigator.getUserMedia) {
  64628. navigator.getUserMedia({
  64629. video: {
  64630. deviceId: constraintsDeviceId,
  64631. width: {
  64632. min: (constraints && constraints.minWidth) || 256,
  64633. max: (constraints && constraints.maxWidth) || 640,
  64634. },
  64635. height: {
  64636. min: (constraints && constraints.minHeight) || 256,
  64637. max: (constraints && constraints.maxHeight) || 480,
  64638. },
  64639. },
  64640. }, function (stream) {
  64641. if (video.mozSrcObject !== undefined) {
  64642. // hack for Firefox < 19
  64643. video.mozSrcObject = stream;
  64644. }
  64645. else {
  64646. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64647. }
  64648. video.play();
  64649. if (onReady) {
  64650. onReady(new VideoTexture("video", video, scene, true, true));
  64651. }
  64652. }, function (e) {
  64653. BABYLON.Tools.Error(e.name);
  64654. });
  64655. }
  64656. }
  64657. };
  64658. return VideoTexture;
  64659. }(BABYLON.Texture));
  64660. BABYLON.VideoTexture = VideoTexture;
  64661. })(BABYLON || (BABYLON = {}));
  64662. //# sourceMappingURL=babylon.videoTexture.js.map
  64663. var BABYLON;
  64664. (function (BABYLON) {
  64665. var RawTexture = /** @class */ (function (_super) {
  64666. __extends(RawTexture, _super);
  64667. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64668. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64669. if (invertY === void 0) { invertY = false; }
  64670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64671. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64672. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64673. _this.format = format;
  64674. _this._engine = scene.getEngine();
  64675. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64676. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64677. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64678. return _this;
  64679. }
  64680. RawTexture.prototype.update = function (data) {
  64681. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64682. };
  64683. // Statics
  64684. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64685. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64686. if (invertY === void 0) { invertY = false; }
  64687. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64688. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64689. };
  64690. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64691. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64692. if (invertY === void 0) { invertY = false; }
  64693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64694. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64695. };
  64696. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64697. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64698. if (invertY === void 0) { invertY = false; }
  64699. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64700. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64701. };
  64702. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64703. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64704. if (invertY === void 0) { invertY = false; }
  64705. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64706. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64707. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64708. };
  64709. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64710. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64711. if (invertY === void 0) { invertY = false; }
  64712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64713. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64714. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64715. };
  64716. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64717. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64718. if (invertY === void 0) { invertY = false; }
  64719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64720. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  64721. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  64722. };
  64723. return RawTexture;
  64724. }(BABYLON.Texture));
  64725. BABYLON.RawTexture = RawTexture;
  64726. })(BABYLON || (BABYLON = {}));
  64727. //# sourceMappingURL=babylon.rawTexture.js.map
  64728. var BABYLON;
  64729. (function (BABYLON) {
  64730. /**
  64731. * Class used to store 3D textures containing user data
  64732. */
  64733. var RawTexture3D = /** @class */ (function (_super) {
  64734. __extends(RawTexture3D, _super);
  64735. /**
  64736. * Create a new RawTexture3D
  64737. * @param data defines the data of the texture
  64738. * @param width defines the width of the texture
  64739. * @param height defines the height of the texture
  64740. * @param depth defines the depth of the texture
  64741. * @param format defines the texture format to use
  64742. * @param scene defines the hosting scene
  64743. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64744. * @param invertY defines if texture must be stored with Y axis inverted
  64745. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64746. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  64747. */
  64748. function RawTexture3D(data, width, height, depth,
  64749. /** Gets or sets the texture format to use */
  64750. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  64751. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64752. if (invertY === void 0) { invertY = false; }
  64753. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64754. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64755. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64756. _this.format = format;
  64757. _this._engine = scene.getEngine();
  64758. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  64759. _this.is3D = true;
  64760. return _this;
  64761. }
  64762. /**
  64763. * Update the texture with new data
  64764. * @param data defines the data to store in the texture
  64765. */
  64766. RawTexture3D.prototype.update = function (data) {
  64767. if (!this._texture) {
  64768. return;
  64769. }
  64770. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64771. };
  64772. return RawTexture3D;
  64773. }(BABYLON.Texture));
  64774. BABYLON.RawTexture3D = RawTexture3D;
  64775. })(BABYLON || (BABYLON = {}));
  64776. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64777. var BABYLON;
  64778. (function (BABYLON) {
  64779. /**
  64780. * PostProcessManager is used to manage one or more post processes or post process pipelines
  64781. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64782. */
  64783. var PostProcessManager = /** @class */ (function () {
  64784. /**
  64785. * Creates a new instance PostProcess
  64786. * @param scene The scene that the post process is associated with.
  64787. */
  64788. function PostProcessManager(scene) {
  64789. this._vertexBuffers = {};
  64790. this._scene = scene;
  64791. }
  64792. PostProcessManager.prototype._prepareBuffers = function () {
  64793. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  64794. return;
  64795. }
  64796. // VBO
  64797. var vertices = [];
  64798. vertices.push(1, 1);
  64799. vertices.push(-1, 1);
  64800. vertices.push(-1, -1);
  64801. vertices.push(1, -1);
  64802. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  64803. this._buildIndexBuffer();
  64804. };
  64805. PostProcessManager.prototype._buildIndexBuffer = function () {
  64806. // Indices
  64807. var indices = [];
  64808. indices.push(0);
  64809. indices.push(1);
  64810. indices.push(2);
  64811. indices.push(0);
  64812. indices.push(2);
  64813. indices.push(3);
  64814. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  64815. };
  64816. /**
  64817. * Rebuilds the vertex buffers of the manager.
  64818. */
  64819. PostProcessManager.prototype._rebuild = function () {
  64820. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64821. if (!vb) {
  64822. return;
  64823. }
  64824. vb._rebuild();
  64825. this._buildIndexBuffer();
  64826. };
  64827. // Methods
  64828. /**
  64829. * Prepares a frame to be run through a post process.
  64830. * @param sourceTexture The input texture to the post procesess. (default: null)
  64831. * @param postProcesses An array of post processes to be run. (default: null)
  64832. * @returns True if the post processes were able to be run.
  64833. */
  64834. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  64835. if (sourceTexture === void 0) { sourceTexture = null; }
  64836. if (postProcesses === void 0) { postProcesses = null; }
  64837. var camera = this._scene.activeCamera;
  64838. if (!camera) {
  64839. return false;
  64840. }
  64841. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64842. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64843. return false;
  64844. }
  64845. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  64846. return true;
  64847. };
  64848. /**
  64849. * Manually render a set of post processes to a texture.
  64850. * @param postProcesses An array of post processes to be run.
  64851. * @param targetTexture The target texture to render to.
  64852. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  64853. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  64854. * @param lodLevel defines which lod of the texture to render to
  64855. */
  64856. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  64857. if (targetTexture === void 0) { targetTexture = null; }
  64858. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64859. if (faceIndex === void 0) { faceIndex = 0; }
  64860. if (lodLevel === void 0) { lodLevel = 0; }
  64861. var engine = this._scene.getEngine();
  64862. for (var index = 0; index < postProcesses.length; index++) {
  64863. if (index < postProcesses.length - 1) {
  64864. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  64865. }
  64866. else {
  64867. if (targetTexture) {
  64868. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  64869. }
  64870. else {
  64871. engine.restoreDefaultFramebuffer();
  64872. }
  64873. }
  64874. var pp = postProcesses[index];
  64875. var effect = pp.apply();
  64876. if (effect) {
  64877. pp.onBeforeRenderObservable.notifyObservers(effect);
  64878. // VBOs
  64879. this._prepareBuffers();
  64880. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64881. // Draw order
  64882. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64883. pp.onAfterRenderObservable.notifyObservers(effect);
  64884. }
  64885. }
  64886. // Restore depth buffer
  64887. engine.setDepthBuffer(true);
  64888. engine.setDepthWrite(true);
  64889. };
  64890. /**
  64891. * Finalize the result of the output of the postprocesses.
  64892. * @param doNotPresent If true the result will not be displayed to the screen.
  64893. * @param targetTexture The target texture to render to.
  64894. * @param faceIndex The index of the face to bind the target texture to.
  64895. * @param postProcesses The array of post processes to render.
  64896. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  64897. */
  64898. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  64899. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  64900. var camera = this._scene.activeCamera;
  64901. if (!camera) {
  64902. return;
  64903. }
  64904. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  64905. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  64906. return;
  64907. }
  64908. var engine = this._scene.getEngine();
  64909. for (var index = 0, len = postProcesses.length; index < len; index++) {
  64910. var pp = postProcesses[index];
  64911. if (index < len - 1) {
  64912. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  64913. }
  64914. else {
  64915. if (targetTexture) {
  64916. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  64917. pp._outputTexture = targetTexture;
  64918. }
  64919. else {
  64920. engine.restoreDefaultFramebuffer();
  64921. pp._outputTexture = null;
  64922. }
  64923. }
  64924. if (doNotPresent) {
  64925. break;
  64926. }
  64927. var effect = pp.apply();
  64928. if (effect) {
  64929. pp.onBeforeRenderObservable.notifyObservers(effect);
  64930. // VBOs
  64931. this._prepareBuffers();
  64932. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  64933. // Draw order
  64934. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  64935. pp.onAfterRenderObservable.notifyObservers(effect);
  64936. }
  64937. }
  64938. // Restore states
  64939. engine.setDepthBuffer(true);
  64940. engine.setDepthWrite(true);
  64941. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  64942. };
  64943. /**
  64944. * Disposes of the post process manager.
  64945. */
  64946. PostProcessManager.prototype.dispose = function () {
  64947. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64948. if (buffer) {
  64949. buffer.dispose();
  64950. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64951. }
  64952. if (this._indexBuffer) {
  64953. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  64954. this._indexBuffer = null;
  64955. }
  64956. };
  64957. return PostProcessManager;
  64958. }());
  64959. BABYLON.PostProcessManager = PostProcessManager;
  64960. })(BABYLON || (BABYLON = {}));
  64961. //# sourceMappingURL=babylon.postProcessManager.js.map
  64962. var BABYLON;
  64963. (function (BABYLON) {
  64964. /**
  64965. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64966. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64967. */
  64968. var PostProcess = /** @class */ (function () {
  64969. /**
  64970. * Creates a new instance PostProcess
  64971. * @param name The name of the PostProcess.
  64972. * @param fragmentUrl The url of the fragment shader to be used.
  64973. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64974. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64975. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64976. * @param camera The camera to apply the render pass to.
  64977. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64978. * @param engine The engine which the post process will be applied. (default: current engine)
  64979. * @param reusable If the post process can be reused on the same frame. (default: false)
  64980. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64981. * @param textureType Type of textures used when performing the post process. (default: 0)
  64982. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64983. * @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
  64984. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64985. */
  64986. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64988. if (defines === void 0) { defines = null; }
  64989. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64990. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64991. if (blockCompilation === void 0) { blockCompilation = false; }
  64992. this.name = name;
  64993. /**
  64994. * Width of the texture to apply the post process on
  64995. */
  64996. this.width = -1;
  64997. /**
  64998. * Height of the texture to apply the post process on
  64999. */
  65000. this.height = -1;
  65001. /**
  65002. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65003. */
  65004. this._outputTexture = null;
  65005. /**
  65006. * If the buffer needs to be cleared before applying the post process. (default: true)
  65007. * Should be set to false if shader will overwrite all previous pixels.
  65008. */
  65009. this.autoClear = true;
  65010. /**
  65011. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65012. */
  65013. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65014. /**
  65015. * Animations to be used for the post processing
  65016. */
  65017. this.animations = new Array();
  65018. /**
  65019. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65020. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65021. */
  65022. this.enablePixelPerfectMode = false;
  65023. /**
  65024. * Force the postprocess to be applied without taking in account viewport
  65025. */
  65026. this.forceFullscreenViewport = true;
  65027. /**
  65028. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65029. *
  65030. * | Value | Type | Description |
  65031. * | ----- | ----------------------------------- | ----------- |
  65032. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65033. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65034. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65035. *
  65036. */
  65037. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65038. /**
  65039. * Force textures to be a power of two (default: false)
  65040. */
  65041. this.alwaysForcePOT = false;
  65042. /**
  65043. * Number of sample textures (default: 1)
  65044. */
  65045. this.samples = 1;
  65046. /**
  65047. * Modify the scale of the post process to be the same as the viewport (default: false)
  65048. */
  65049. this.adaptScaleToCurrentViewport = false;
  65050. this._reusable = false;
  65051. /**
  65052. * Smart array of input and output textures for the post process.
  65053. */
  65054. this._textures = new BABYLON.SmartArray(2);
  65055. /**
  65056. * The index in _textures that corresponds to the output texture.
  65057. */
  65058. this._currentRenderTextureInd = 0;
  65059. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65060. this._texelSize = BABYLON.Vector2.Zero();
  65061. // Events
  65062. /**
  65063. * An event triggered when the postprocess is activated.
  65064. */
  65065. this.onActivateObservable = new BABYLON.Observable();
  65066. /**
  65067. * An event triggered when the postprocess changes its size.
  65068. */
  65069. this.onSizeChangedObservable = new BABYLON.Observable();
  65070. /**
  65071. * An event triggered when the postprocess applies its effect.
  65072. */
  65073. this.onApplyObservable = new BABYLON.Observable();
  65074. /**
  65075. * An event triggered before rendering the postprocess
  65076. */
  65077. this.onBeforeRenderObservable = new BABYLON.Observable();
  65078. /**
  65079. * An event triggered after rendering the postprocess
  65080. */
  65081. this.onAfterRenderObservable = new BABYLON.Observable();
  65082. if (camera != null) {
  65083. this._camera = camera;
  65084. this._scene = camera.getScene();
  65085. camera.attachPostProcess(this);
  65086. this._engine = this._scene.getEngine();
  65087. this._scene.postProcesses.push(this);
  65088. }
  65089. else if (engine) {
  65090. this._engine = engine;
  65091. this._engine.postProcesses.push(this);
  65092. }
  65093. this._options = options;
  65094. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65095. this._reusable = reusable || false;
  65096. this._textureType = textureType;
  65097. this._samplers = samplers || [];
  65098. this._samplers.push("textureSampler");
  65099. this._fragmentUrl = fragmentUrl;
  65100. this._vertexUrl = vertexUrl;
  65101. this._parameters = parameters || [];
  65102. this._parameters.push("scale");
  65103. this._indexParameters = indexParameters;
  65104. if (!blockCompilation) {
  65105. this.updateEffect(defines);
  65106. }
  65107. }
  65108. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65109. /**
  65110. * A function that is added to the onActivateObservable
  65111. */
  65112. set: function (callback) {
  65113. if (this._onActivateObserver) {
  65114. this.onActivateObservable.remove(this._onActivateObserver);
  65115. }
  65116. if (callback) {
  65117. this._onActivateObserver = this.onActivateObservable.add(callback);
  65118. }
  65119. },
  65120. enumerable: true,
  65121. configurable: true
  65122. });
  65123. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65124. /**
  65125. * A function that is added to the onSizeChangedObservable
  65126. */
  65127. set: function (callback) {
  65128. if (this._onSizeChangedObserver) {
  65129. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65130. }
  65131. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65132. },
  65133. enumerable: true,
  65134. configurable: true
  65135. });
  65136. Object.defineProperty(PostProcess.prototype, "onApply", {
  65137. /**
  65138. * A function that is added to the onApplyObservable
  65139. */
  65140. set: function (callback) {
  65141. if (this._onApplyObserver) {
  65142. this.onApplyObservable.remove(this._onApplyObserver);
  65143. }
  65144. this._onApplyObserver = this.onApplyObservable.add(callback);
  65145. },
  65146. enumerable: true,
  65147. configurable: true
  65148. });
  65149. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65150. /**
  65151. * A function that is added to the onBeforeRenderObservable
  65152. */
  65153. set: function (callback) {
  65154. if (this._onBeforeRenderObserver) {
  65155. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65156. }
  65157. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65158. },
  65159. enumerable: true,
  65160. configurable: true
  65161. });
  65162. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65163. /**
  65164. * A function that is added to the onAfterRenderObservable
  65165. */
  65166. set: function (callback) {
  65167. if (this._onAfterRenderObserver) {
  65168. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65169. }
  65170. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65171. },
  65172. enumerable: true,
  65173. configurable: true
  65174. });
  65175. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65176. /**
  65177. * 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
  65178. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65179. */
  65180. get: function () {
  65181. return this._textures.data[this._currentRenderTextureInd];
  65182. },
  65183. set: function (value) {
  65184. this._forcedOutputTexture = value;
  65185. },
  65186. enumerable: true,
  65187. configurable: true
  65188. });
  65189. /**
  65190. * Gets the camera which post process is applied to.
  65191. * @returns The camera the post process is applied to.
  65192. */
  65193. PostProcess.prototype.getCamera = function () {
  65194. return this._camera;
  65195. };
  65196. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65197. /**
  65198. * Gets the texel size of the postprocess.
  65199. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65200. */
  65201. get: function () {
  65202. if (this._shareOutputWithPostProcess) {
  65203. return this._shareOutputWithPostProcess.texelSize;
  65204. }
  65205. if (this._forcedOutputTexture) {
  65206. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65207. }
  65208. return this._texelSize;
  65209. },
  65210. enumerable: true,
  65211. configurable: true
  65212. });
  65213. /**
  65214. * Gets the engine which this post process belongs to.
  65215. * @returns The engine the post process was enabled with.
  65216. */
  65217. PostProcess.prototype.getEngine = function () {
  65218. return this._engine;
  65219. };
  65220. /**
  65221. * The effect that is created when initializing the post process.
  65222. * @returns The created effect corrisponding the the postprocess.
  65223. */
  65224. PostProcess.prototype.getEffect = function () {
  65225. return this._effect;
  65226. };
  65227. /**
  65228. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65229. * @param postProcess The post process to share the output with.
  65230. * @returns This post process.
  65231. */
  65232. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65233. this._disposeTextures();
  65234. this._shareOutputWithPostProcess = postProcess;
  65235. return this;
  65236. };
  65237. /**
  65238. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65239. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65240. */
  65241. PostProcess.prototype.useOwnOutput = function () {
  65242. if (this._textures.length == 0) {
  65243. this._textures = new BABYLON.SmartArray(2);
  65244. }
  65245. this._shareOutputWithPostProcess = null;
  65246. };
  65247. /**
  65248. * Updates the effect with the current post process compile time values and recompiles the shader.
  65249. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65250. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65251. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65252. * @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
  65253. * @param onCompiled Called when the shader has been compiled.
  65254. * @param onError Called if there is an error when compiling a shader.
  65255. */
  65256. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65257. if (defines === void 0) { defines = null; }
  65258. if (uniforms === void 0) { uniforms = null; }
  65259. if (samplers === void 0) { samplers = null; }
  65260. 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);
  65261. };
  65262. /**
  65263. * The post process is reusable if it can be used multiple times within one frame.
  65264. * @returns If the post process is reusable
  65265. */
  65266. PostProcess.prototype.isReusable = function () {
  65267. return this._reusable;
  65268. };
  65269. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65270. PostProcess.prototype.markTextureDirty = function () {
  65271. this.width = -1;
  65272. };
  65273. /**
  65274. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65275. * 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.
  65276. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65277. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65278. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65279. * @returns The target texture that was bound to be written to.
  65280. */
  65281. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65282. var _this = this;
  65283. if (sourceTexture === void 0) { sourceTexture = null; }
  65284. camera = camera || this._camera;
  65285. var scene = camera.getScene();
  65286. var engine = scene.getEngine();
  65287. var maxSize = engine.getCaps().maxTextureSize;
  65288. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65289. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65290. // 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
  65291. var webVRCamera = camera.parent;
  65292. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65293. requiredWidth /= 2;
  65294. }
  65295. var desiredWidth = (this._options.width || requiredWidth);
  65296. var desiredHeight = this._options.height || requiredHeight;
  65297. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65298. if (this.adaptScaleToCurrentViewport) {
  65299. var currentViewport = engine.currentViewport;
  65300. if (currentViewport) {
  65301. desiredWidth *= currentViewport.width;
  65302. desiredHeight *= currentViewport.height;
  65303. }
  65304. }
  65305. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65306. if (!this._options.width) {
  65307. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65308. }
  65309. if (!this._options.height) {
  65310. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65311. }
  65312. }
  65313. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65314. if (this._textures.length > 0) {
  65315. for (var i = 0; i < this._textures.length; i++) {
  65316. this._engine._releaseTexture(this._textures.data[i]);
  65317. }
  65318. this._textures.reset();
  65319. }
  65320. this.width = desiredWidth;
  65321. this.height = desiredHeight;
  65322. var textureSize = { width: this.width, height: this.height };
  65323. var textureOptions = {
  65324. generateMipMaps: false,
  65325. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65326. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65327. samplingMode: this.renderTargetSamplingMode,
  65328. type: this._textureType
  65329. };
  65330. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65331. if (this._reusable) {
  65332. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65333. }
  65334. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65335. this.onSizeChangedObservable.notifyObservers(this);
  65336. }
  65337. this._textures.forEach(function (texture) {
  65338. if (texture.samples !== _this.samples) {
  65339. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65340. }
  65341. });
  65342. }
  65343. var target;
  65344. if (this._shareOutputWithPostProcess) {
  65345. target = this._shareOutputWithPostProcess.inputTexture;
  65346. }
  65347. else if (this._forcedOutputTexture) {
  65348. target = this._forcedOutputTexture;
  65349. this.width = this._forcedOutputTexture.width;
  65350. this.height = this._forcedOutputTexture.height;
  65351. }
  65352. else {
  65353. target = this.inputTexture;
  65354. }
  65355. // Bind the input of this post process to be used as the output of the previous post process.
  65356. if (this.enablePixelPerfectMode) {
  65357. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65358. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65359. }
  65360. else {
  65361. this._scaleRatio.copyFromFloats(1, 1);
  65362. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65363. }
  65364. this.onActivateObservable.notifyObservers(camera);
  65365. // Clear
  65366. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65367. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65368. }
  65369. if (this._reusable) {
  65370. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65371. }
  65372. return target;
  65373. };
  65374. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65375. /**
  65376. * If the post process is supported.
  65377. */
  65378. get: function () {
  65379. return this._effect.isSupported;
  65380. },
  65381. enumerable: true,
  65382. configurable: true
  65383. });
  65384. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65385. /**
  65386. * The aspect ratio of the output texture.
  65387. */
  65388. get: function () {
  65389. if (this._shareOutputWithPostProcess) {
  65390. return this._shareOutputWithPostProcess.aspectRatio;
  65391. }
  65392. if (this._forcedOutputTexture) {
  65393. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65394. }
  65395. return this.width / this.height;
  65396. },
  65397. enumerable: true,
  65398. configurable: true
  65399. });
  65400. /**
  65401. * Get a value indicating if the post-process is ready to be used
  65402. * @returns true if the post-process is ready (shader is compiled)
  65403. */
  65404. PostProcess.prototype.isReady = function () {
  65405. return this._effect && this._effect.isReady();
  65406. };
  65407. /**
  65408. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65409. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65410. */
  65411. PostProcess.prototype.apply = function () {
  65412. // Check
  65413. if (!this._effect || !this._effect.isReady())
  65414. return null;
  65415. // States
  65416. this._engine.enableEffect(this._effect);
  65417. this._engine.setState(false);
  65418. this._engine.setDepthBuffer(false);
  65419. this._engine.setDepthWrite(false);
  65420. // Alpha
  65421. this._engine.setAlphaMode(this.alphaMode);
  65422. if (this.alphaConstants) {
  65423. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65424. }
  65425. // Bind the output texture of the preivous post process as the input to this post process.
  65426. var source;
  65427. if (this._shareOutputWithPostProcess) {
  65428. source = this._shareOutputWithPostProcess.inputTexture;
  65429. }
  65430. else if (this._forcedOutputTexture) {
  65431. source = this._forcedOutputTexture;
  65432. }
  65433. else {
  65434. source = this.inputTexture;
  65435. }
  65436. this._effect._bindTexture("textureSampler", source);
  65437. // Parameters
  65438. this._effect.setVector2("scale", this._scaleRatio);
  65439. this.onApplyObservable.notifyObservers(this._effect);
  65440. return this._effect;
  65441. };
  65442. PostProcess.prototype._disposeTextures = function () {
  65443. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65444. return;
  65445. }
  65446. if (this._textures.length > 0) {
  65447. for (var i = 0; i < this._textures.length; i++) {
  65448. this._engine._releaseTexture(this._textures.data[i]);
  65449. }
  65450. }
  65451. this._textures.dispose();
  65452. };
  65453. /**
  65454. * Disposes the post process.
  65455. * @param camera The camera to dispose the post process on.
  65456. */
  65457. PostProcess.prototype.dispose = function (camera) {
  65458. camera = camera || this._camera;
  65459. this._disposeTextures();
  65460. if (this._scene) {
  65461. var index_1 = this._scene.postProcesses.indexOf(this);
  65462. if (index_1 !== -1) {
  65463. this._scene.postProcesses.splice(index_1, 1);
  65464. }
  65465. }
  65466. else {
  65467. var index_2 = this._engine.postProcesses.indexOf(this);
  65468. if (index_2 !== -1) {
  65469. this._engine.postProcesses.splice(index_2, 1);
  65470. }
  65471. }
  65472. if (!camera) {
  65473. return;
  65474. }
  65475. camera.detachPostProcess(this);
  65476. var index = camera._postProcesses.indexOf(this);
  65477. if (index === 0 && camera._postProcesses.length > 0) {
  65478. var firstPostProcess = this._camera._getFirstPostProcess();
  65479. if (firstPostProcess) {
  65480. firstPostProcess.markTextureDirty();
  65481. }
  65482. }
  65483. this.onActivateObservable.clear();
  65484. this.onAfterRenderObservable.clear();
  65485. this.onApplyObservable.clear();
  65486. this.onBeforeRenderObservable.clear();
  65487. this.onSizeChangedObservable.clear();
  65488. };
  65489. return PostProcess;
  65490. }());
  65491. BABYLON.PostProcess = PostProcess;
  65492. })(BABYLON || (BABYLON = {}));
  65493. //# sourceMappingURL=babylon.postProcess.js.map
  65494. var BABYLON;
  65495. (function (BABYLON) {
  65496. var PassPostProcess = /** @class */ (function (_super) {
  65497. __extends(PassPostProcess, _super);
  65498. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65499. if (camera === void 0) { camera = null; }
  65500. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65501. if (blockCompilation === void 0) { blockCompilation = false; }
  65502. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65503. }
  65504. return PassPostProcess;
  65505. }(BABYLON.PostProcess));
  65506. BABYLON.PassPostProcess = PassPostProcess;
  65507. })(BABYLON || (BABYLON = {}));
  65508. //# sourceMappingURL=babylon.passPostProcess.js.map
  65509. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65510. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65511. s = arguments[i];
  65512. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65513. t[p] = s[p];
  65514. }
  65515. return t;
  65516. };
  65517. var BABYLON;
  65518. (function (BABYLON) {
  65519. /**
  65520. * Default implementation IShadowGenerator.
  65521. * This is the main object responsible of generating shadows in the framework.
  65522. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65523. */
  65524. var ShadowGenerator = /** @class */ (function () {
  65525. /**
  65526. * Creates a ShadowGenerator object.
  65527. * A ShadowGenerator is the required tool to use the shadows.
  65528. * Each light casting shadows needs to use its own ShadowGenerator.
  65529. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65530. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65531. * @param light The light object generating the shadows.
  65532. * @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.
  65533. */
  65534. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65535. this._bias = 0.00005;
  65536. this._normalBias = 0;
  65537. this._blurBoxOffset = 1;
  65538. this._blurScale = 2;
  65539. this._blurKernel = 1;
  65540. this._useKernelBlur = false;
  65541. this._filter = ShadowGenerator.FILTER_NONE;
  65542. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65543. this._contactHardeningLightSizeUVRatio = 0.1;
  65544. this._darkness = 0;
  65545. this._transparencyShadow = false;
  65546. /**
  65547. * Controls the extent to which the shadows fade out at the edge of the frustum
  65548. * Used only by directionals and spots
  65549. */
  65550. this.frustumEdgeFalloff = 0;
  65551. /**
  65552. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65553. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65554. * It might on the other hand introduce peter panning.
  65555. */
  65556. this.forceBackFacesOnly = false;
  65557. this._lightDirection = BABYLON.Vector3.Zero();
  65558. this._viewMatrix = BABYLON.Matrix.Zero();
  65559. this._projectionMatrix = BABYLON.Matrix.Zero();
  65560. this._transformMatrix = BABYLON.Matrix.Zero();
  65561. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65562. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65563. this._currentFaceIndex = 0;
  65564. this._currentFaceIndexCache = 0;
  65565. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65566. this._mapSize = mapSize;
  65567. this._light = light;
  65568. this._scene = light.getScene();
  65569. light._shadowGenerator = this;
  65570. // Texture type fallback from float to int if not supported.
  65571. var caps = this._scene.getEngine().getCaps();
  65572. if (!useFullFloatFirst) {
  65573. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65574. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65575. }
  65576. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65577. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65578. }
  65579. else {
  65580. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65581. }
  65582. }
  65583. else {
  65584. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65585. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65586. }
  65587. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65588. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65589. }
  65590. else {
  65591. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65592. }
  65593. }
  65594. this._initializeGenerator();
  65595. this._applyFilterValues();
  65596. }
  65597. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65598. /**
  65599. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65600. */
  65601. get: function () {
  65602. return this._bias;
  65603. },
  65604. /**
  65605. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65606. */
  65607. set: function (bias) {
  65608. this._bias = bias;
  65609. },
  65610. enumerable: true,
  65611. configurable: true
  65612. });
  65613. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65614. /**
  65615. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65616. */
  65617. get: function () {
  65618. return this._normalBias;
  65619. },
  65620. /**
  65621. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65622. */
  65623. set: function (normalBias) {
  65624. this._normalBias = normalBias;
  65625. },
  65626. enumerable: true,
  65627. configurable: true
  65628. });
  65629. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65630. /**
  65631. * Gets the blur box offset: offset applied during the blur pass.
  65632. * Only usefull if useKernelBlur = false
  65633. */
  65634. get: function () {
  65635. return this._blurBoxOffset;
  65636. },
  65637. /**
  65638. * Sets the blur box offset: offset applied during the blur pass.
  65639. * Only usefull if useKernelBlur = false
  65640. */
  65641. set: function (value) {
  65642. if (this._blurBoxOffset === value) {
  65643. return;
  65644. }
  65645. this._blurBoxOffset = value;
  65646. this._disposeBlurPostProcesses();
  65647. },
  65648. enumerable: true,
  65649. configurable: true
  65650. });
  65651. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65652. /**
  65653. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65654. * 2 means half of the size.
  65655. */
  65656. get: function () {
  65657. return this._blurScale;
  65658. },
  65659. /**
  65660. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65661. * 2 means half of the size.
  65662. */
  65663. set: function (value) {
  65664. if (this._blurScale === value) {
  65665. return;
  65666. }
  65667. this._blurScale = value;
  65668. this._disposeBlurPostProcesses();
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65674. /**
  65675. * Gets the blur kernel: kernel size of the blur pass.
  65676. * Only usefull if useKernelBlur = true
  65677. */
  65678. get: function () {
  65679. return this._blurKernel;
  65680. },
  65681. /**
  65682. * Sets the blur kernel: kernel size of the blur pass.
  65683. * Only usefull if useKernelBlur = true
  65684. */
  65685. set: function (value) {
  65686. if (this._blurKernel === value) {
  65687. return;
  65688. }
  65689. this._blurKernel = value;
  65690. this._disposeBlurPostProcesses();
  65691. },
  65692. enumerable: true,
  65693. configurable: true
  65694. });
  65695. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65696. /**
  65697. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65698. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65699. */
  65700. get: function () {
  65701. return this._useKernelBlur;
  65702. },
  65703. /**
  65704. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65705. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65706. */
  65707. set: function (value) {
  65708. if (this._useKernelBlur === value) {
  65709. return;
  65710. }
  65711. this._useKernelBlur = value;
  65712. this._disposeBlurPostProcesses();
  65713. },
  65714. enumerable: true,
  65715. configurable: true
  65716. });
  65717. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65718. /**
  65719. * Gets the depth scale used in ESM mode.
  65720. */
  65721. get: function () {
  65722. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65723. },
  65724. /**
  65725. * Sets the depth scale used in ESM mode.
  65726. * This can override the scale stored on the light.
  65727. */
  65728. set: function (value) {
  65729. this._depthScale = value;
  65730. },
  65731. enumerable: true,
  65732. configurable: true
  65733. });
  65734. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65735. /**
  65736. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65737. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65738. */
  65739. get: function () {
  65740. return this._filter;
  65741. },
  65742. /**
  65743. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65744. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65745. */
  65746. set: function (value) {
  65747. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65748. if (this._light.needCube()) {
  65749. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65750. this.useExponentialShadowMap = true;
  65751. return;
  65752. }
  65753. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65754. this.useCloseExponentialShadowMap = true;
  65755. return;
  65756. }
  65757. // PCF on cubemap would also be expensive
  65758. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65759. this.usePoissonSampling = true;
  65760. return;
  65761. }
  65762. }
  65763. // Weblg1 fallback for PCF.
  65764. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65765. if (this._scene.getEngine().webGLVersion === 1) {
  65766. this.usePoissonSampling = true;
  65767. return;
  65768. }
  65769. }
  65770. if (this._filter === value) {
  65771. return;
  65772. }
  65773. this._filter = value;
  65774. this._disposeBlurPostProcesses();
  65775. this._applyFilterValues();
  65776. this._light._markMeshesAsLightDirty();
  65777. },
  65778. enumerable: true,
  65779. configurable: true
  65780. });
  65781. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65782. /**
  65783. * Gets if the current filter is set to Poisson Sampling.
  65784. */
  65785. get: function () {
  65786. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65787. },
  65788. /**
  65789. * Sets the current filter to Poisson Sampling.
  65790. */
  65791. set: function (value) {
  65792. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65793. return;
  65794. }
  65795. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65796. },
  65797. enumerable: true,
  65798. configurable: true
  65799. });
  65800. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65801. /**
  65802. * Gets if the current filter is set to VSM.
  65803. * DEPRECATED. Should use useExponentialShadowMap instead.
  65804. */
  65805. get: function () {
  65806. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65807. return this.useExponentialShadowMap;
  65808. },
  65809. /**
  65810. * Sets the current filter is to VSM.
  65811. * DEPRECATED. Should use useExponentialShadowMap instead.
  65812. */
  65813. set: function (value) {
  65814. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65815. this.useExponentialShadowMap = value;
  65816. },
  65817. enumerable: true,
  65818. configurable: true
  65819. });
  65820. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65821. /**
  65822. * Gets if the current filter is set to blurred VSM.
  65823. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65824. */
  65825. get: function () {
  65826. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65827. return this.useBlurExponentialShadowMap;
  65828. },
  65829. /**
  65830. * Sets the current filter is to blurred VSM.
  65831. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65832. */
  65833. set: function (value) {
  65834. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65835. this.useBlurExponentialShadowMap = value;
  65836. },
  65837. enumerable: true,
  65838. configurable: true
  65839. });
  65840. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65841. /**
  65842. * Gets if the current filter is set to ESM.
  65843. */
  65844. get: function () {
  65845. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65846. },
  65847. /**
  65848. * Sets the current filter is to ESM.
  65849. */
  65850. set: function (value) {
  65851. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65852. return;
  65853. }
  65854. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65855. },
  65856. enumerable: true,
  65857. configurable: true
  65858. });
  65859. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65860. /**
  65861. * Gets if the current filter is set to filtered ESM.
  65862. */
  65863. get: function () {
  65864. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65865. },
  65866. /**
  65867. * Gets if the current filter is set to filtered ESM.
  65868. */
  65869. set: function (value) {
  65870. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65871. return;
  65872. }
  65873. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65874. },
  65875. enumerable: true,
  65876. configurable: true
  65877. });
  65878. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65879. /**
  65880. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65881. * exponential to prevent steep falloff artifacts).
  65882. */
  65883. get: function () {
  65884. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65885. },
  65886. /**
  65887. * Sets the current filter to "close ESM" (using the inverse of the
  65888. * exponential to prevent steep falloff artifacts).
  65889. */
  65890. set: function (value) {
  65891. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65892. return;
  65893. }
  65894. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65895. },
  65896. enumerable: true,
  65897. configurable: true
  65898. });
  65899. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65900. /**
  65901. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65902. * exponential to prevent steep falloff artifacts).
  65903. */
  65904. get: function () {
  65905. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65906. },
  65907. /**
  65908. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65909. * exponential to prevent steep falloff artifacts).
  65910. */
  65911. set: function (value) {
  65912. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65913. return;
  65914. }
  65915. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65916. },
  65917. enumerable: true,
  65918. configurable: true
  65919. });
  65920. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65921. /**
  65922. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65923. */
  65924. get: function () {
  65925. return this.filter === ShadowGenerator.FILTER_PCF;
  65926. },
  65927. /**
  65928. * Sets the current filter to "PCF" (percentage closer filtering).
  65929. */
  65930. set: function (value) {
  65931. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65932. return;
  65933. }
  65934. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65935. },
  65936. enumerable: true,
  65937. configurable: true
  65938. });
  65939. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65940. /**
  65941. * Gets the PCF or PCSS Quality.
  65942. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65943. */
  65944. get: function () {
  65945. return this._filteringQuality;
  65946. },
  65947. /**
  65948. * Sets the PCF or PCSS Quality.
  65949. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65950. */
  65951. set: function (filteringQuality) {
  65952. this._filteringQuality = filteringQuality;
  65953. },
  65954. enumerable: true,
  65955. configurable: true
  65956. });
  65957. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65958. /**
  65959. * Gets if the current filter is set to "PCSS" (contact hardening).
  65960. */
  65961. get: function () {
  65962. return this.filter === ShadowGenerator.FILTER_PCSS;
  65963. },
  65964. /**
  65965. * Sets the current filter to "PCSS" (contact hardening).
  65966. */
  65967. set: function (value) {
  65968. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65969. return;
  65970. }
  65971. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65972. },
  65973. enumerable: true,
  65974. configurable: true
  65975. });
  65976. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65977. /**
  65978. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65979. * Using a ratio helps keeping shape stability independently of the map size.
  65980. *
  65981. * It does not account for the light projection as it was having too much
  65982. * instability during the light setup or during light position changes.
  65983. *
  65984. * Only valid if useContactHardeningShadow is true.
  65985. */
  65986. get: function () {
  65987. return this._contactHardeningLightSizeUVRatio;
  65988. },
  65989. /**
  65990. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65991. * Using a ratio helps keeping shape stability independently of the map size.
  65992. *
  65993. * It does not account for the light projection as it was having too much
  65994. * instability during the light setup or during light position changes.
  65995. *
  65996. * Only valid if useContactHardeningShadow is true.
  65997. */
  65998. set: function (contactHardeningLightSizeUVRatio) {
  65999. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66000. },
  66001. enumerable: true,
  66002. configurable: true
  66003. });
  66004. /**
  66005. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66006. * 0 means strongest and 1 would means no shadow.
  66007. * @returns the darkness.
  66008. */
  66009. ShadowGenerator.prototype.getDarkness = function () {
  66010. return this._darkness;
  66011. };
  66012. /**
  66013. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66014. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66015. * @returns the shadow generator allowing fluent coding.
  66016. */
  66017. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66018. if (darkness >= 1.0)
  66019. this._darkness = 1.0;
  66020. else if (darkness <= 0.0)
  66021. this._darkness = 0.0;
  66022. else
  66023. this._darkness = darkness;
  66024. return this;
  66025. };
  66026. /**
  66027. * Sets the ability to have transparent shadow (boolean).
  66028. * @param transparent True if transparent else False
  66029. * @returns the shadow generator allowing fluent coding
  66030. */
  66031. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66032. this._transparencyShadow = transparent;
  66033. return this;
  66034. };
  66035. /**
  66036. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66037. * @returns The render target texture if present otherwise, null
  66038. */
  66039. ShadowGenerator.prototype.getShadowMap = function () {
  66040. return this._shadowMap;
  66041. };
  66042. /**
  66043. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66044. * @returns The render target texture if the shadow map is present otherwise, null
  66045. */
  66046. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66047. if (this._shadowMap2) {
  66048. return this._shadowMap2;
  66049. }
  66050. return this._shadowMap;
  66051. };
  66052. /**
  66053. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66054. * @param mesh Mesh to add
  66055. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66056. * @returns the Shadow Generator itself
  66057. */
  66058. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66059. if (includeDescendants === void 0) { includeDescendants = true; }
  66060. if (!this._shadowMap) {
  66061. return this;
  66062. }
  66063. if (!this._shadowMap.renderList) {
  66064. this._shadowMap.renderList = [];
  66065. }
  66066. this._shadowMap.renderList.push(mesh);
  66067. if (includeDescendants) {
  66068. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66069. }
  66070. return this;
  66071. var _a;
  66072. };
  66073. /**
  66074. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66075. * @param mesh Mesh to remove
  66076. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66077. * @returns the Shadow Generator itself
  66078. */
  66079. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66080. if (includeDescendants === void 0) { includeDescendants = true; }
  66081. if (!this._shadowMap || !this._shadowMap.renderList) {
  66082. return this;
  66083. }
  66084. var index = this._shadowMap.renderList.indexOf(mesh);
  66085. if (index !== -1) {
  66086. this._shadowMap.renderList.splice(index, 1);
  66087. }
  66088. if (includeDescendants) {
  66089. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66090. var child = _a[_i];
  66091. this.removeShadowCaster(child);
  66092. }
  66093. }
  66094. return this;
  66095. };
  66096. /**
  66097. * Returns the associated light object.
  66098. * @returns the light generating the shadow
  66099. */
  66100. ShadowGenerator.prototype.getLight = function () {
  66101. return this._light;
  66102. };
  66103. ShadowGenerator.prototype._initializeGenerator = function () {
  66104. this._light._markMeshesAsLightDirty();
  66105. this._initializeShadowMap();
  66106. };
  66107. ShadowGenerator.prototype._initializeShadowMap = function () {
  66108. var _this = this;
  66109. // Render target
  66110. var engine = this._scene.getEngine();
  66111. if (engine.webGLVersion > 1) {
  66112. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66113. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66114. }
  66115. else {
  66116. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66117. }
  66118. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66119. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66120. this._shadowMap.anisotropicFilteringLevel = 1;
  66121. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66122. this._shadowMap.renderParticles = false;
  66123. this._shadowMap.ignoreCameraViewport = true;
  66124. // Record Face Index before render.
  66125. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66126. _this._currentFaceIndex = faceIndex;
  66127. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66128. engine.setColorWrite(false);
  66129. }
  66130. });
  66131. // Custom render function.
  66132. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66133. // Blur if required afer render.
  66134. this._shadowMap.onAfterUnbindObservable.add(function () {
  66135. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66136. engine.setColorWrite(true);
  66137. }
  66138. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66139. return;
  66140. }
  66141. var shadowMap = _this.getShadowMapForRendering();
  66142. if (shadowMap) {
  66143. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66144. }
  66145. });
  66146. // Clear according to the chosen filter.
  66147. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66148. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66149. this._shadowMap.onClearObservable.add(function (engine) {
  66150. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66151. engine.clear(clearOne, false, true, false);
  66152. }
  66153. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66154. engine.clear(clearZero, true, true, false);
  66155. }
  66156. else {
  66157. engine.clear(clearOne, true, true, false);
  66158. }
  66159. });
  66160. };
  66161. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66162. var _this = this;
  66163. var engine = this._scene.getEngine();
  66164. var targetSize = this._mapSize / this.blurScale;
  66165. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66166. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66167. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66168. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66169. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66170. }
  66171. if (this.useKernelBlur) {
  66172. 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);
  66173. this._kernelBlurXPostprocess.width = targetSize;
  66174. this._kernelBlurXPostprocess.height = targetSize;
  66175. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66176. effect.setTexture("textureSampler", _this._shadowMap);
  66177. });
  66178. 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);
  66179. this._kernelBlurXPostprocess.autoClear = false;
  66180. this._kernelBlurYPostprocess.autoClear = false;
  66181. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66182. this._kernelBlurXPostprocess.packedFloat = true;
  66183. this._kernelBlurYPostprocess.packedFloat = true;
  66184. }
  66185. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66186. }
  66187. else {
  66188. 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);
  66189. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66190. effect.setFloat2("screenSize", targetSize, targetSize);
  66191. effect.setTexture("textureSampler", _this._shadowMap);
  66192. });
  66193. this._boxBlurPostprocess.autoClear = false;
  66194. this._blurPostProcesses = [this._boxBlurPostprocess];
  66195. }
  66196. };
  66197. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66198. var index;
  66199. var engine = this._scene.getEngine();
  66200. if (depthOnlySubMeshes.length) {
  66201. engine.setColorWrite(false);
  66202. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66203. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66204. }
  66205. engine.setColorWrite(true);
  66206. }
  66207. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66208. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66209. }
  66210. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66211. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66212. }
  66213. if (this._transparencyShadow) {
  66214. for (index = 0; index < transparentSubMeshes.length; index++) {
  66215. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66216. }
  66217. }
  66218. };
  66219. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66220. var _this = this;
  66221. var mesh = subMesh.getRenderingMesh();
  66222. var scene = this._scene;
  66223. var engine = scene.getEngine();
  66224. var material = subMesh.getMaterial();
  66225. if (!material) {
  66226. return;
  66227. }
  66228. // Culling
  66229. engine.setState(material.backFaceCulling);
  66230. // Managing instances
  66231. var batch = mesh._getInstancesRenderList(subMesh._id);
  66232. if (batch.mustReturn) {
  66233. return;
  66234. }
  66235. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66236. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66237. engine.enableEffect(this._effect);
  66238. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66239. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66240. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66241. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66242. this._effect.setVector3("lightData", this._cachedDirection);
  66243. }
  66244. else {
  66245. this._effect.setVector3("lightData", this._cachedPosition);
  66246. }
  66247. if (scene.activeCamera) {
  66248. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66249. }
  66250. // Alpha test
  66251. if (material && material.needAlphaTesting()) {
  66252. var alphaTexture = material.getAlphaTestTexture();
  66253. if (alphaTexture) {
  66254. this._effect.setTexture("diffuseSampler", alphaTexture);
  66255. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66256. }
  66257. }
  66258. // Bones
  66259. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66260. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66261. }
  66262. // Morph targets
  66263. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66264. if (this.forceBackFacesOnly) {
  66265. engine.setState(true, 0, false, true);
  66266. }
  66267. // Draw
  66268. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66269. if (this.forceBackFacesOnly) {
  66270. engine.setState(true, 0, false, false);
  66271. }
  66272. }
  66273. else {
  66274. // Need to reset refresh rate of the shadowMap
  66275. if (this._shadowMap) {
  66276. this._shadowMap.resetRefreshCounter();
  66277. }
  66278. }
  66279. };
  66280. ShadowGenerator.prototype._applyFilterValues = function () {
  66281. if (!this._shadowMap) {
  66282. return;
  66283. }
  66284. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66285. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66286. }
  66287. else {
  66288. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66289. }
  66290. };
  66291. /**
  66292. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66293. * @param onCompiled Callback triggered at the and of the effects compilation
  66294. * @param options Sets of optional options forcing the compilation with different modes
  66295. */
  66296. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66297. var _this = this;
  66298. var localOptions = __assign({ useInstances: false }, options);
  66299. var shadowMap = this.getShadowMap();
  66300. if (!shadowMap) {
  66301. if (onCompiled) {
  66302. onCompiled(this);
  66303. }
  66304. return;
  66305. }
  66306. var renderList = shadowMap.renderList;
  66307. if (!renderList) {
  66308. if (onCompiled) {
  66309. onCompiled(this);
  66310. }
  66311. return;
  66312. }
  66313. var subMeshes = new Array();
  66314. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66315. var mesh = renderList_1[_i];
  66316. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66317. }
  66318. if (subMeshes.length === 0) {
  66319. if (onCompiled) {
  66320. onCompiled(this);
  66321. }
  66322. return;
  66323. }
  66324. var currentIndex = 0;
  66325. var checkReady = function () {
  66326. if (!_this._scene || !_this._scene.getEngine()) {
  66327. return;
  66328. }
  66329. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66330. currentIndex++;
  66331. if (currentIndex >= subMeshes.length) {
  66332. if (onCompiled) {
  66333. onCompiled(_this);
  66334. }
  66335. return;
  66336. }
  66337. }
  66338. setTimeout(checkReady, 16);
  66339. };
  66340. checkReady();
  66341. };
  66342. /**
  66343. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66344. * @param options Sets of optional options forcing the compilation with different modes
  66345. * @returns A promise that resolves when the compilation completes
  66346. */
  66347. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66348. var _this = this;
  66349. return new Promise(function (resolve) {
  66350. _this.forceCompilation(function () {
  66351. resolve();
  66352. }, options);
  66353. });
  66354. };
  66355. /**
  66356. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66357. * @param subMesh The submesh we want to render in the shadow map
  66358. * @param useInstances Defines wether will draw in the map using instances
  66359. * @returns true if ready otherwise, false
  66360. */
  66361. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66362. var defines = [];
  66363. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66364. defines.push("#define FLOAT");
  66365. }
  66366. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66367. defines.push("#define ESM");
  66368. }
  66369. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66370. defines.push("#define DEPTHTEXTURE");
  66371. }
  66372. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66373. var mesh = subMesh.getMesh();
  66374. var material = subMesh.getMaterial();
  66375. // Normal bias.
  66376. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66377. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66378. defines.push("#define NORMAL");
  66379. if (mesh.nonUniformScaling) {
  66380. defines.push("#define NONUNIFORMSCALING");
  66381. }
  66382. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66383. defines.push("#define DIRECTIONINLIGHTDATA");
  66384. }
  66385. }
  66386. // Alpha test
  66387. if (material && material.needAlphaTesting()) {
  66388. var alphaTexture = material.getAlphaTestTexture();
  66389. if (alphaTexture) {
  66390. defines.push("#define ALPHATEST");
  66391. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66392. attribs.push(BABYLON.VertexBuffer.UVKind);
  66393. defines.push("#define UV1");
  66394. }
  66395. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66396. if (alphaTexture.coordinatesIndex === 1) {
  66397. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66398. defines.push("#define UV2");
  66399. }
  66400. }
  66401. }
  66402. }
  66403. // Bones
  66404. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66405. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66406. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66407. if (mesh.numBoneInfluencers > 4) {
  66408. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66409. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66410. }
  66411. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66412. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66413. }
  66414. else {
  66415. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66416. }
  66417. // Morph targets
  66418. var manager = mesh.morphTargetManager;
  66419. var morphInfluencers = 0;
  66420. if (manager) {
  66421. if (manager.numInfluencers > 0) {
  66422. defines.push("#define MORPHTARGETS");
  66423. morphInfluencers = manager.numInfluencers;
  66424. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66425. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66426. }
  66427. }
  66428. // Instances
  66429. if (useInstances) {
  66430. defines.push("#define INSTANCES");
  66431. attribs.push("world0");
  66432. attribs.push("world1");
  66433. attribs.push("world2");
  66434. attribs.push("world3");
  66435. }
  66436. // Get correct effect
  66437. var join = defines.join("\n");
  66438. if (this._cachedDefines !== join) {
  66439. this._cachedDefines = join;
  66440. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66441. }
  66442. if (!this._effect.isReady()) {
  66443. return false;
  66444. }
  66445. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66446. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66447. this._initializeBlurRTTAndPostProcesses();
  66448. }
  66449. }
  66450. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66451. return false;
  66452. }
  66453. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66454. return false;
  66455. }
  66456. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66457. return false;
  66458. }
  66459. return true;
  66460. };
  66461. /**
  66462. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66463. * @param defines Defines of the material we want to update
  66464. * @param lightIndex Index of the light in the enabled light list of the material
  66465. */
  66466. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66467. var scene = this._scene;
  66468. var light = this._light;
  66469. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66470. return;
  66471. }
  66472. defines["SHADOW" + lightIndex] = true;
  66473. if (this.useContactHardeningShadow) {
  66474. defines["SHADOWPCSS" + lightIndex] = true;
  66475. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66476. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66477. }
  66478. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66479. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66480. }
  66481. // else default to high.
  66482. }
  66483. if (this.usePercentageCloserFiltering) {
  66484. defines["SHADOWPCF" + lightIndex] = true;
  66485. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66486. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66487. }
  66488. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66489. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66490. }
  66491. // else default to high.
  66492. }
  66493. else if (this.usePoissonSampling) {
  66494. defines["SHADOWPOISSON" + lightIndex] = true;
  66495. }
  66496. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66497. defines["SHADOWESM" + lightIndex] = true;
  66498. }
  66499. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66500. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66501. }
  66502. if (light.needCube()) {
  66503. defines["SHADOWCUBE" + lightIndex] = true;
  66504. }
  66505. };
  66506. /**
  66507. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66508. * defined in the generator but impacting the effect).
  66509. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66510. * @param effect The effect we are binfing the information for
  66511. */
  66512. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66513. var light = this._light;
  66514. var scene = this._scene;
  66515. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66516. return;
  66517. }
  66518. var camera = scene.activeCamera;
  66519. if (!camera) {
  66520. return;
  66521. }
  66522. var shadowMap = this.getShadowMap();
  66523. if (!shadowMap) {
  66524. return;
  66525. }
  66526. if (!light.needCube()) {
  66527. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66528. }
  66529. // Only PCF uses depth stencil texture.
  66530. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66531. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66532. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66533. }
  66534. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66535. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66536. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66537. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66538. }
  66539. else {
  66540. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66541. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66542. }
  66543. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66544. };
  66545. /**
  66546. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66547. * (eq to shadow prjection matrix * light transform matrix)
  66548. * @returns The transform matrix used to create the shadow map
  66549. */
  66550. ShadowGenerator.prototype.getTransformMatrix = function () {
  66551. var scene = this._scene;
  66552. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66553. return this._transformMatrix;
  66554. }
  66555. this._currentRenderID = scene.getRenderId();
  66556. this._currentFaceIndexCache = this._currentFaceIndex;
  66557. var lightPosition = this._light.position;
  66558. if (this._light.computeTransformedInformation()) {
  66559. lightPosition = this._light.transformedPosition;
  66560. }
  66561. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66562. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66563. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66564. }
  66565. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66566. this._cachedPosition.copyFrom(lightPosition);
  66567. this._cachedDirection.copyFrom(this._lightDirection);
  66568. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66569. var shadowMap = this.getShadowMap();
  66570. if (shadowMap) {
  66571. var renderList = shadowMap.renderList;
  66572. if (renderList) {
  66573. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66574. }
  66575. }
  66576. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66577. }
  66578. return this._transformMatrix;
  66579. };
  66580. /**
  66581. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66582. * Cube and 2D textures for instance.
  66583. */
  66584. ShadowGenerator.prototype.recreateShadowMap = function () {
  66585. var shadowMap = this._shadowMap;
  66586. if (!shadowMap) {
  66587. return;
  66588. }
  66589. // Track render list.
  66590. var renderList = shadowMap.renderList;
  66591. // Clean up existing data.
  66592. this._disposeRTTandPostProcesses();
  66593. // Reinitializes.
  66594. this._initializeGenerator();
  66595. // Reaffect the filter to ensure a correct fallback if necessary.
  66596. this.filter = this.filter;
  66597. // Reaffect the filter.
  66598. this._applyFilterValues();
  66599. // Reaffect Render List.
  66600. this._shadowMap.renderList = renderList;
  66601. };
  66602. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66603. if (this._shadowMap2) {
  66604. this._shadowMap2.dispose();
  66605. this._shadowMap2 = null;
  66606. }
  66607. if (this._boxBlurPostprocess) {
  66608. this._boxBlurPostprocess.dispose();
  66609. this._boxBlurPostprocess = null;
  66610. }
  66611. if (this._kernelBlurXPostprocess) {
  66612. this._kernelBlurXPostprocess.dispose();
  66613. this._kernelBlurXPostprocess = null;
  66614. }
  66615. if (this._kernelBlurYPostprocess) {
  66616. this._kernelBlurYPostprocess.dispose();
  66617. this._kernelBlurYPostprocess = null;
  66618. }
  66619. this._blurPostProcesses = [];
  66620. };
  66621. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66622. if (this._shadowMap) {
  66623. this._shadowMap.dispose();
  66624. this._shadowMap = null;
  66625. }
  66626. this._disposeBlurPostProcesses();
  66627. };
  66628. /**
  66629. * Disposes the ShadowGenerator.
  66630. * Returns nothing.
  66631. */
  66632. ShadowGenerator.prototype.dispose = function () {
  66633. this._disposeRTTandPostProcesses();
  66634. if (this._light) {
  66635. this._light._shadowGenerator = null;
  66636. this._light._markMeshesAsLightDirty();
  66637. }
  66638. };
  66639. /**
  66640. * Serializes the shadow generator setup to a json object.
  66641. * @returns The serialized JSON object
  66642. */
  66643. ShadowGenerator.prototype.serialize = function () {
  66644. var serializationObject = {};
  66645. var shadowMap = this.getShadowMap();
  66646. if (!shadowMap) {
  66647. return serializationObject;
  66648. }
  66649. serializationObject.lightId = this._light.id;
  66650. serializationObject.mapSize = shadowMap.getRenderSize();
  66651. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66652. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66653. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66654. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66655. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66656. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66657. serializationObject.depthScale = this.depthScale;
  66658. serializationObject.darkness = this.getDarkness();
  66659. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66660. serializationObject.blurKernel = this.blurKernel;
  66661. serializationObject.blurScale = this.blurScale;
  66662. serializationObject.useKernelBlur = this.useKernelBlur;
  66663. serializationObject.transparencyShadow = this._transparencyShadow;
  66664. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66665. serializationObject.bias = this.bias;
  66666. serializationObject.normalBias = this.normalBias;
  66667. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66668. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66669. serializationObject.filteringQuality = this.filteringQuality;
  66670. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66671. serializationObject.renderList = [];
  66672. if (shadowMap.renderList) {
  66673. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66674. var mesh = shadowMap.renderList[meshIndex];
  66675. serializationObject.renderList.push(mesh.id);
  66676. }
  66677. }
  66678. return serializationObject;
  66679. };
  66680. /**
  66681. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66682. * @param parsedShadowGenerator The JSON object to parse
  66683. * @param scene The scene to create the shadow map for
  66684. * @returns The parsed shadow generator
  66685. */
  66686. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66687. //casting to point light, as light is missing the position attr and typescript complains.
  66688. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66689. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66690. var shadowMap = shadowGenerator.getShadowMap();
  66691. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66692. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66693. meshes.forEach(function (mesh) {
  66694. if (!shadowMap) {
  66695. return;
  66696. }
  66697. if (!shadowMap.renderList) {
  66698. shadowMap.renderList = [];
  66699. }
  66700. shadowMap.renderList.push(mesh);
  66701. });
  66702. }
  66703. if (parsedShadowGenerator.usePoissonSampling) {
  66704. shadowGenerator.usePoissonSampling = true;
  66705. }
  66706. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66707. shadowGenerator.useExponentialShadowMap = true;
  66708. }
  66709. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66710. shadowGenerator.useBlurExponentialShadowMap = true;
  66711. }
  66712. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66713. shadowGenerator.useCloseExponentialShadowMap = true;
  66714. }
  66715. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66716. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66717. }
  66718. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66719. shadowGenerator.usePercentageCloserFiltering = true;
  66720. }
  66721. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66722. shadowGenerator.useContactHardeningShadow = true;
  66723. }
  66724. if (parsedShadowGenerator.filteringQuality) {
  66725. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66726. }
  66727. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66728. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66729. }
  66730. // Backward compat
  66731. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66732. shadowGenerator.useExponentialShadowMap = true;
  66733. }
  66734. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66735. shadowGenerator.useBlurExponentialShadowMap = true;
  66736. }
  66737. if (parsedShadowGenerator.depthScale) {
  66738. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66739. }
  66740. if (parsedShadowGenerator.blurScale) {
  66741. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66742. }
  66743. if (parsedShadowGenerator.blurBoxOffset) {
  66744. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66745. }
  66746. if (parsedShadowGenerator.useKernelBlur) {
  66747. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66748. }
  66749. if (parsedShadowGenerator.blurKernel) {
  66750. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66751. }
  66752. if (parsedShadowGenerator.bias !== undefined) {
  66753. shadowGenerator.bias = parsedShadowGenerator.bias;
  66754. }
  66755. if (parsedShadowGenerator.normalBias !== undefined) {
  66756. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66757. }
  66758. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  66759. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  66760. }
  66761. if (parsedShadowGenerator.darkness) {
  66762. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66763. }
  66764. if (parsedShadowGenerator.transparencyShadow) {
  66765. shadowGenerator.setTransparencyShadow(true);
  66766. }
  66767. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66768. return shadowGenerator;
  66769. };
  66770. /**
  66771. * Shadow generator mode None: no filtering applied.
  66772. */
  66773. ShadowGenerator.FILTER_NONE = 0;
  66774. /**
  66775. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66776. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66777. */
  66778. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66779. /**
  66780. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66781. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66782. */
  66783. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66784. /**
  66785. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66786. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66787. */
  66788. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66789. /**
  66790. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66791. * edge artifacts on steep falloff.
  66792. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66793. */
  66794. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66795. /**
  66796. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66797. * edge artifacts on steep falloff.
  66798. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66799. */
  66800. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66801. /**
  66802. * Shadow generator mode PCF: Percentage Closer Filtering
  66803. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66804. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66805. */
  66806. ShadowGenerator.FILTER_PCF = 6;
  66807. /**
  66808. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66809. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66810. * Contact Hardening
  66811. */
  66812. ShadowGenerator.FILTER_PCSS = 7;
  66813. /**
  66814. * Reserved for PCF and PCSS
  66815. * Highest Quality.
  66816. *
  66817. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66818. *
  66819. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66820. */
  66821. ShadowGenerator.QUALITY_HIGH = 0;
  66822. /**
  66823. * Reserved for PCF and PCSS
  66824. * Good tradeoff for quality/perf cross devices
  66825. *
  66826. * Execute PCF on a 3*3 kernel.
  66827. *
  66828. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66829. */
  66830. ShadowGenerator.QUALITY_MEDIUM = 1;
  66831. /**
  66832. * Reserved for PCF and PCSS
  66833. * The lowest quality but the fastest.
  66834. *
  66835. * Execute PCF on a 1*1 kernel.
  66836. *
  66837. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66838. */
  66839. ShadowGenerator.QUALITY_LOW = 2;
  66840. return ShadowGenerator;
  66841. }());
  66842. BABYLON.ShadowGenerator = ShadowGenerator;
  66843. })(BABYLON || (BABYLON = {}));
  66844. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66845. var BABYLON;
  66846. (function (BABYLON) {
  66847. var DefaultLoadingScreen = /** @class */ (function () {
  66848. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66849. if (_loadingText === void 0) { _loadingText = ""; }
  66850. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66851. var _this = this;
  66852. this._renderingCanvas = _renderingCanvas;
  66853. this._loadingText = _loadingText;
  66854. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66855. // Resize
  66856. this._resizeLoadingUI = function () {
  66857. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66858. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66859. if (!_this._loadingDiv) {
  66860. return;
  66861. }
  66862. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66863. _this._loadingDiv.style.left = canvasRect.left + "px";
  66864. _this._loadingDiv.style.top = canvasRect.top + "px";
  66865. _this._loadingDiv.style.width = canvasRect.width + "px";
  66866. _this._loadingDiv.style.height = canvasRect.height + "px";
  66867. };
  66868. }
  66869. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66870. if (this._loadingDiv) {
  66871. // Do not add a loading screen if there is already one
  66872. return;
  66873. }
  66874. this._loadingDiv = document.createElement("div");
  66875. this._loadingDiv.id = "babylonjsLoadingDiv";
  66876. this._loadingDiv.style.opacity = "0";
  66877. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66878. this._loadingDiv.style.pointerEvents = "none";
  66879. // Loading text
  66880. this._loadingTextDiv = document.createElement("div");
  66881. this._loadingTextDiv.style.position = "absolute";
  66882. this._loadingTextDiv.style.left = "0";
  66883. this._loadingTextDiv.style.top = "50%";
  66884. this._loadingTextDiv.style.marginTop = "80px";
  66885. this._loadingTextDiv.style.width = "100%";
  66886. this._loadingTextDiv.style.height = "20px";
  66887. this._loadingTextDiv.style.fontFamily = "Arial";
  66888. this._loadingTextDiv.style.fontSize = "14px";
  66889. this._loadingTextDiv.style.color = "white";
  66890. this._loadingTextDiv.style.textAlign = "center";
  66891. this._loadingTextDiv.innerHTML = "Loading";
  66892. this._loadingDiv.appendChild(this._loadingTextDiv);
  66893. //set the predefined text
  66894. this._loadingTextDiv.innerHTML = this._loadingText;
  66895. // Generating keyframes
  66896. var style = document.createElement('style');
  66897. style.type = 'text/css';
  66898. 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 }";
  66899. style.innerHTML = keyFrames;
  66900. document.getElementsByTagName('head')[0].appendChild(style);
  66901. // Loading img
  66902. var imgBack = new Image();
  66903. 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";
  66904. imgBack.style.position = "absolute";
  66905. imgBack.style.left = "50%";
  66906. imgBack.style.top = "50%";
  66907. imgBack.style.marginLeft = "-60px";
  66908. imgBack.style.marginTop = "-60px";
  66909. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66910. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66911. imgBack.style.transformOrigin = "50% 50%";
  66912. imgBack.style.webkitTransformOrigin = "50% 50%";
  66913. this._loadingDiv.appendChild(imgBack);
  66914. this._resizeLoadingUI();
  66915. window.addEventListener("resize", this._resizeLoadingUI);
  66916. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66917. document.body.appendChild(this._loadingDiv);
  66918. this._loadingDiv.style.opacity = "1";
  66919. };
  66920. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66921. var _this = this;
  66922. if (!this._loadingDiv) {
  66923. return;
  66924. }
  66925. var onTransitionEnd = function () {
  66926. if (!_this._loadingDiv) {
  66927. return;
  66928. }
  66929. document.body.removeChild(_this._loadingDiv);
  66930. window.removeEventListener("resize", _this._resizeLoadingUI);
  66931. _this._loadingDiv = null;
  66932. };
  66933. this._loadingDiv.style.opacity = "0";
  66934. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66935. };
  66936. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66937. set: function (text) {
  66938. this._loadingText = text;
  66939. if (this._loadingTextDiv) {
  66940. this._loadingTextDiv.innerHTML = this._loadingText;
  66941. }
  66942. },
  66943. enumerable: true,
  66944. configurable: true
  66945. });
  66946. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66947. get: function () {
  66948. return this._loadingDivBackgroundColor;
  66949. },
  66950. set: function (color) {
  66951. this._loadingDivBackgroundColor = color;
  66952. if (!this._loadingDiv) {
  66953. return;
  66954. }
  66955. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. return DefaultLoadingScreen;
  66961. }());
  66962. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66963. })(BABYLON || (BABYLON = {}));
  66964. //# sourceMappingURL=babylon.loadingScreen.js.map
  66965. var BABYLON;
  66966. (function (BABYLON) {
  66967. var SceneLoaderProgressEvent = /** @class */ (function () {
  66968. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66969. this.lengthComputable = lengthComputable;
  66970. this.loaded = loaded;
  66971. this.total = total;
  66972. }
  66973. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66974. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66975. };
  66976. return SceneLoaderProgressEvent;
  66977. }());
  66978. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66979. var SceneLoader = /** @class */ (function () {
  66980. function SceneLoader() {
  66981. }
  66982. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66983. get: function () {
  66984. return 0;
  66985. },
  66986. enumerable: true,
  66987. configurable: true
  66988. });
  66989. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66990. get: function () {
  66991. return 1;
  66992. },
  66993. enumerable: true,
  66994. configurable: true
  66995. });
  66996. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66997. get: function () {
  66998. return 2;
  66999. },
  67000. enumerable: true,
  67001. configurable: true
  67002. });
  67003. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67004. get: function () {
  67005. return 3;
  67006. },
  67007. enumerable: true,
  67008. configurable: true
  67009. });
  67010. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67011. get: function () {
  67012. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67013. },
  67014. set: function (value) {
  67015. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67016. },
  67017. enumerable: true,
  67018. configurable: true
  67019. });
  67020. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67021. get: function () {
  67022. return SceneLoader._ShowLoadingScreen;
  67023. },
  67024. set: function (value) {
  67025. SceneLoader._ShowLoadingScreen = value;
  67026. },
  67027. enumerable: true,
  67028. configurable: true
  67029. });
  67030. Object.defineProperty(SceneLoader, "loggingLevel", {
  67031. get: function () {
  67032. return SceneLoader._loggingLevel;
  67033. },
  67034. set: function (value) {
  67035. SceneLoader._loggingLevel = value;
  67036. },
  67037. enumerable: true,
  67038. configurable: true
  67039. });
  67040. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67041. get: function () {
  67042. return SceneLoader._CleanBoneMatrixWeights;
  67043. },
  67044. set: function (value) {
  67045. SceneLoader._CleanBoneMatrixWeights = value;
  67046. },
  67047. enumerable: true,
  67048. configurable: true
  67049. });
  67050. SceneLoader._getDefaultPlugin = function () {
  67051. return SceneLoader._registeredPlugins[".babylon"];
  67052. };
  67053. SceneLoader._getPluginForExtension = function (extension) {
  67054. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67055. if (registeredPlugin) {
  67056. return registeredPlugin;
  67057. }
  67058. 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");
  67059. return SceneLoader._getDefaultPlugin();
  67060. };
  67061. SceneLoader._getPluginForDirectLoad = function (data) {
  67062. for (var extension in SceneLoader._registeredPlugins) {
  67063. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67064. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67065. return SceneLoader._registeredPlugins[extension];
  67066. }
  67067. }
  67068. return SceneLoader._getDefaultPlugin();
  67069. };
  67070. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67071. if (sceneFilename.name) {
  67072. sceneFilename = sceneFilename.name;
  67073. }
  67074. var queryStringPosition = sceneFilename.indexOf("?");
  67075. if (queryStringPosition !== -1) {
  67076. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67077. }
  67078. var dotPosition = sceneFilename.lastIndexOf(".");
  67079. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67080. return SceneLoader._getPluginForExtension(extension);
  67081. };
  67082. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67083. SceneLoader._getDirectLoad = function (sceneFilename) {
  67084. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67085. return sceneFilename.substr(5);
  67086. }
  67087. return null;
  67088. };
  67089. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67090. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67091. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67092. var plugin;
  67093. if (registeredPlugin.plugin.createPlugin) {
  67094. plugin = registeredPlugin.plugin.createPlugin();
  67095. }
  67096. else {
  67097. plugin = registeredPlugin.plugin;
  67098. }
  67099. var useArrayBuffer = registeredPlugin.isBinary;
  67100. var database;
  67101. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67102. var dataCallback = function (data, responseURL) {
  67103. if (scene.isDisposed) {
  67104. onError("Scene has been disposed");
  67105. return;
  67106. }
  67107. scene.database = database;
  67108. onSuccess(plugin, data, responseURL);
  67109. };
  67110. var request = null;
  67111. var pluginDisposed = false;
  67112. var onDisposeObservable = plugin.onDisposeObservable;
  67113. if (onDisposeObservable) {
  67114. onDisposeObservable.add(function () {
  67115. pluginDisposed = true;
  67116. if (request) {
  67117. request.abort();
  67118. request = null;
  67119. }
  67120. onDispose();
  67121. });
  67122. }
  67123. var manifestChecked = function () {
  67124. if (pluginDisposed) {
  67125. return;
  67126. }
  67127. var url = rootUrl + sceneFilename;
  67128. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67129. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67130. } : undefined, database, useArrayBuffer, function (request, exception) {
  67131. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67132. });
  67133. };
  67134. if (directLoad) {
  67135. dataCallback(directLoad);
  67136. return plugin;
  67137. }
  67138. if (rootUrl.indexOf("file:") === -1) {
  67139. var engine = scene.getEngine();
  67140. var canUseOfflineSupport = engine.enableOfflineSupport;
  67141. if (canUseOfflineSupport) {
  67142. // Also check for exceptions
  67143. var exceptionFound = false;
  67144. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67145. var regex = _a[_i];
  67146. if (regex.test(rootUrl + sceneFilename)) {
  67147. exceptionFound = true;
  67148. break;
  67149. }
  67150. }
  67151. canUseOfflineSupport = !exceptionFound;
  67152. }
  67153. if (canUseOfflineSupport) {
  67154. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67155. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67156. }
  67157. else {
  67158. manifestChecked();
  67159. }
  67160. }
  67161. // Loading file from disk via input file or drag'n'drop
  67162. else {
  67163. var fileOrString = sceneFilename;
  67164. if (fileOrString.name) { // File
  67165. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67166. }
  67167. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67168. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67169. }
  67170. else {
  67171. onError("Unable to find file named " + sceneFilename);
  67172. }
  67173. }
  67174. return plugin;
  67175. };
  67176. // Public functions
  67177. SceneLoader.GetPluginForExtension = function (extension) {
  67178. return SceneLoader._getPluginForExtension(extension).plugin;
  67179. };
  67180. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67181. return !!SceneLoader._registeredPlugins[extension];
  67182. };
  67183. SceneLoader.RegisterPlugin = function (plugin) {
  67184. if (typeof plugin.extensions === "string") {
  67185. var extension = plugin.extensions;
  67186. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67187. plugin: plugin,
  67188. isBinary: false
  67189. };
  67190. }
  67191. else {
  67192. var extensions = plugin.extensions;
  67193. Object.keys(extensions).forEach(function (extension) {
  67194. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67195. plugin: plugin,
  67196. isBinary: extensions[extension].isBinary
  67197. };
  67198. });
  67199. }
  67200. };
  67201. /**
  67202. * Import meshes into a scene
  67203. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67204. * @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)
  67205. * @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)
  67206. * @param scene the instance of BABYLON.Scene to append to
  67207. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67208. * @param onProgress a callback with a progress event for each file being loaded
  67209. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67210. * @param pluginExtension the extension used to determine the plugin
  67211. * @returns The loaded plugin
  67212. */
  67213. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67214. if (sceneFilename === void 0) { sceneFilename = ""; }
  67215. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67216. if (onSuccess === void 0) { onSuccess = null; }
  67217. if (onProgress === void 0) { onProgress = null; }
  67218. if (onError === void 0) { onError = null; }
  67219. if (pluginExtension === void 0) { pluginExtension = null; }
  67220. if (!scene) {
  67221. BABYLON.Tools.Error("No scene available to import mesh to");
  67222. return null;
  67223. }
  67224. if (!sceneFilename) {
  67225. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67226. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67227. }
  67228. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67229. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67230. return null;
  67231. }
  67232. var loadingToken = {};
  67233. scene._addPendingData(loadingToken);
  67234. var disposeHandler = function () {
  67235. scene._removePendingData(loadingToken);
  67236. };
  67237. var errorHandler = function (message, exception) {
  67238. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67239. if (onError) {
  67240. onError(scene, errorMessage, exception);
  67241. }
  67242. else {
  67243. BABYLON.Tools.Error(errorMessage);
  67244. // should the exception be thrown?
  67245. }
  67246. disposeHandler();
  67247. };
  67248. var progressHandler = onProgress ? function (event) {
  67249. try {
  67250. onProgress(event);
  67251. }
  67252. catch (e) {
  67253. errorHandler("Error in onProgress callback", e);
  67254. }
  67255. } : undefined;
  67256. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67257. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67258. if (onSuccess) {
  67259. try {
  67260. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67261. }
  67262. catch (e) {
  67263. errorHandler("Error in onSuccess callback", e);
  67264. }
  67265. }
  67266. scene._removePendingData(loadingToken);
  67267. };
  67268. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67269. if (plugin.rewriteRootURL) {
  67270. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67271. }
  67272. if (sceneFilename === "") {
  67273. if (sceneFilename === "") {
  67274. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67275. }
  67276. }
  67277. if (plugin.importMesh) {
  67278. var syncedPlugin = plugin;
  67279. var meshes = new Array();
  67280. var particleSystems = new Array();
  67281. var skeletons = new Array();
  67282. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67283. return;
  67284. }
  67285. scene.loadingPluginName = plugin.name;
  67286. successHandler(meshes, particleSystems, skeletons, []);
  67287. }
  67288. else {
  67289. var asyncedPlugin = plugin;
  67290. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67291. scene.loadingPluginName = plugin.name;
  67292. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67293. }).catch(function (error) {
  67294. errorHandler(error.message, error);
  67295. });
  67296. }
  67297. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67298. };
  67299. /**
  67300. * Import meshes into a scene
  67301. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67302. * @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)
  67303. * @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)
  67304. * @param scene the instance of BABYLON.Scene to append to
  67305. * @param onProgress a callback with a progress event for each file being loaded
  67306. * @param pluginExtension the extension used to determine the plugin
  67307. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67308. */
  67309. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67310. if (sceneFilename === void 0) { sceneFilename = ""; }
  67311. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67312. if (onProgress === void 0) { onProgress = null; }
  67313. if (pluginExtension === void 0) { pluginExtension = null; }
  67314. return new Promise(function (resolve, reject) {
  67315. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67316. resolve({
  67317. meshes: meshes,
  67318. particleSystems: particleSystems,
  67319. skeletons: skeletons,
  67320. animationGroups: animationGroups
  67321. });
  67322. }, onProgress, function (scene, message, exception) {
  67323. reject(exception || new Error(message));
  67324. }, pluginExtension);
  67325. });
  67326. };
  67327. /**
  67328. * Load a scene
  67329. * @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)
  67330. * @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)
  67331. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67332. * @param onSuccess a callback with the scene when import succeeds
  67333. * @param onProgress a callback with a progress event for each file being loaded
  67334. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67335. * @param pluginExtension the extension used to determine the plugin
  67336. * @returns The loaded plugin
  67337. */
  67338. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67339. if (onSuccess === void 0) { onSuccess = null; }
  67340. if (onProgress === void 0) { onProgress = null; }
  67341. if (onError === void 0) { onError = null; }
  67342. if (pluginExtension === void 0) { pluginExtension = null; }
  67343. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67344. };
  67345. /**
  67346. * Load a scene
  67347. * @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)
  67348. * @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)
  67349. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67350. * @param onProgress a callback with a progress event for each file being loaded
  67351. * @param pluginExtension the extension used to determine the plugin
  67352. * @returns The loaded scene
  67353. */
  67354. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67355. if (onProgress === void 0) { onProgress = null; }
  67356. if (pluginExtension === void 0) { pluginExtension = null; }
  67357. return new Promise(function (resolve, reject) {
  67358. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67359. resolve(scene);
  67360. }, onProgress, function (scene, message, exception) {
  67361. reject(exception || new Error(message));
  67362. }, pluginExtension);
  67363. });
  67364. };
  67365. /**
  67366. * Append a scene
  67367. * @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)
  67368. * @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)
  67369. * @param scene is the instance of BABYLON.Scene to append to
  67370. * @param onSuccess a callback with the scene when import succeeds
  67371. * @param onProgress a callback with a progress event for each file being loaded
  67372. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67373. * @param pluginExtension the extension used to determine the plugin
  67374. * @returns The loaded plugin
  67375. */
  67376. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67377. if (sceneFilename === void 0) { sceneFilename = ""; }
  67378. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67379. if (onSuccess === void 0) { onSuccess = null; }
  67380. if (onProgress === void 0) { onProgress = null; }
  67381. if (onError === void 0) { onError = null; }
  67382. if (pluginExtension === void 0) { pluginExtension = null; }
  67383. if (!scene) {
  67384. BABYLON.Tools.Error("No scene available to append to");
  67385. return null;
  67386. }
  67387. if (!sceneFilename) {
  67388. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67389. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67390. }
  67391. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67392. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67393. return null;
  67394. }
  67395. if (SceneLoader.ShowLoadingScreen) {
  67396. scene.getEngine().displayLoadingUI();
  67397. }
  67398. var loadingToken = {};
  67399. scene._addPendingData(loadingToken);
  67400. var disposeHandler = function () {
  67401. scene._removePendingData(loadingToken);
  67402. scene.getEngine().hideLoadingUI();
  67403. };
  67404. var errorHandler = function (message, exception) {
  67405. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67406. if (onError) {
  67407. onError(scene, errorMessage, exception);
  67408. }
  67409. else {
  67410. BABYLON.Tools.Error(errorMessage);
  67411. // should the exception be thrown?
  67412. }
  67413. disposeHandler();
  67414. };
  67415. var progressHandler = onProgress ? function (event) {
  67416. try {
  67417. onProgress(event);
  67418. }
  67419. catch (e) {
  67420. errorHandler("Error in onProgress callback", e);
  67421. }
  67422. } : undefined;
  67423. var successHandler = function () {
  67424. if (onSuccess) {
  67425. try {
  67426. onSuccess(scene);
  67427. }
  67428. catch (e) {
  67429. errorHandler("Error in onSuccess callback", e);
  67430. }
  67431. }
  67432. scene._removePendingData(loadingToken);
  67433. };
  67434. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67435. if (sceneFilename === "") {
  67436. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67437. }
  67438. if (plugin.load) {
  67439. var syncedPlugin = plugin;
  67440. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67441. return;
  67442. }
  67443. scene.loadingPluginName = plugin.name;
  67444. successHandler();
  67445. }
  67446. else {
  67447. var asyncedPlugin = plugin;
  67448. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67449. scene.loadingPluginName = plugin.name;
  67450. successHandler();
  67451. }).catch(function (error) {
  67452. errorHandler(error.message, error);
  67453. });
  67454. }
  67455. if (SceneLoader.ShowLoadingScreen) {
  67456. scene.executeWhenReady(function () {
  67457. scene.getEngine().hideLoadingUI();
  67458. });
  67459. }
  67460. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67461. };
  67462. /**
  67463. * Append a scene
  67464. * @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)
  67465. * @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)
  67466. * @param scene is the instance of BABYLON.Scene to append to
  67467. * @param onProgress a callback with a progress event for each file being loaded
  67468. * @param pluginExtension the extension used to determine the plugin
  67469. * @returns The given scene
  67470. */
  67471. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67472. if (sceneFilename === void 0) { sceneFilename = ""; }
  67473. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67474. if (onProgress === void 0) { onProgress = null; }
  67475. if (pluginExtension === void 0) { pluginExtension = null; }
  67476. return new Promise(function (resolve, reject) {
  67477. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67478. resolve(scene);
  67479. }, onProgress, function (scene, message, exception) {
  67480. reject(exception || new Error(message));
  67481. }, pluginExtension);
  67482. });
  67483. };
  67484. /**
  67485. * Load a scene into an asset container
  67486. * @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)
  67487. * @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)
  67488. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67489. * @param onSuccess a callback with the scene when import succeeds
  67490. * @param onProgress a callback with a progress event for each file being loaded
  67491. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67492. * @param pluginExtension the extension used to determine the plugin
  67493. * @returns The loaded plugin
  67494. */
  67495. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67496. if (sceneFilename === void 0) { sceneFilename = ""; }
  67497. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67498. if (onSuccess === void 0) { onSuccess = null; }
  67499. if (onProgress === void 0) { onProgress = null; }
  67500. if (onError === void 0) { onError = null; }
  67501. if (pluginExtension === void 0) { pluginExtension = null; }
  67502. if (!scene) {
  67503. BABYLON.Tools.Error("No scene available to load asset container to");
  67504. return null;
  67505. }
  67506. if (!sceneFilename) {
  67507. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67508. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67509. }
  67510. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67511. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67512. return null;
  67513. }
  67514. var loadingToken = {};
  67515. scene._addPendingData(loadingToken);
  67516. var disposeHandler = function () {
  67517. scene._removePendingData(loadingToken);
  67518. };
  67519. var errorHandler = function (message, exception) {
  67520. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67521. if (onError) {
  67522. onError(scene, errorMessage, exception);
  67523. }
  67524. else {
  67525. BABYLON.Tools.Error(errorMessage);
  67526. // should the exception be thrown?
  67527. }
  67528. disposeHandler();
  67529. };
  67530. var progressHandler = onProgress ? function (event) {
  67531. try {
  67532. onProgress(event);
  67533. }
  67534. catch (e) {
  67535. errorHandler("Error in onProgress callback", e);
  67536. }
  67537. } : undefined;
  67538. var successHandler = function (assets) {
  67539. if (onSuccess) {
  67540. try {
  67541. onSuccess(assets);
  67542. }
  67543. catch (e) {
  67544. errorHandler("Error in onSuccess callback", e);
  67545. }
  67546. }
  67547. scene._removePendingData(loadingToken);
  67548. };
  67549. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67550. if (plugin.loadAssetContainer) {
  67551. var syncedPlugin = plugin;
  67552. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67553. if (!assetContainer) {
  67554. return;
  67555. }
  67556. scene.loadingPluginName = plugin.name;
  67557. successHandler(assetContainer);
  67558. }
  67559. else if (plugin.loadAssetContainerAsync) {
  67560. var asyncedPlugin = plugin;
  67561. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67562. scene.loadingPluginName = plugin.name;
  67563. successHandler(assetContainer);
  67564. }).catch(function (error) {
  67565. errorHandler(error.message, error);
  67566. });
  67567. }
  67568. else {
  67569. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67570. }
  67571. if (SceneLoader.ShowLoadingScreen) {
  67572. scene.executeWhenReady(function () {
  67573. scene.getEngine().hideLoadingUI();
  67574. });
  67575. }
  67576. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67577. };
  67578. /**
  67579. * Load a scene into an asset container
  67580. * @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)
  67581. * @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)
  67582. * @param scene is the instance of BABYLON.Scene to append to
  67583. * @param onProgress a callback with a progress event for each file being loaded
  67584. * @param pluginExtension the extension used to determine the plugin
  67585. * @returns The loaded asset container
  67586. */
  67587. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67588. if (sceneFilename === void 0) { sceneFilename = ""; }
  67589. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67590. if (onProgress === void 0) { onProgress = null; }
  67591. if (pluginExtension === void 0) { pluginExtension = null; }
  67592. return new Promise(function (resolve, reject) {
  67593. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67594. resolve(assetContainer);
  67595. }, onProgress, function (scene, message, exception) {
  67596. reject(exception || new Error(message));
  67597. }, pluginExtension);
  67598. });
  67599. };
  67600. // Flags
  67601. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67602. SceneLoader._ShowLoadingScreen = true;
  67603. SceneLoader._CleanBoneMatrixWeights = false;
  67604. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67605. // Members
  67606. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67607. SceneLoader._registeredPlugins = {};
  67608. return SceneLoader;
  67609. }());
  67610. BABYLON.SceneLoader = SceneLoader;
  67611. ;
  67612. })(BABYLON || (BABYLON = {}));
  67613. //# sourceMappingURL=babylon.sceneLoader.js.map
  67614. var BABYLON;
  67615. (function (BABYLON) {
  67616. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67617. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67618. var parsedMaterial = parsedData.materials[index];
  67619. if (parsedMaterial.id === id) {
  67620. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67621. }
  67622. }
  67623. return null;
  67624. };
  67625. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67626. for (var i in names) {
  67627. if (mesh.name === names[i]) {
  67628. hierarchyIds.push(mesh.id);
  67629. return true;
  67630. }
  67631. }
  67632. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67633. hierarchyIds.push(mesh.id);
  67634. return true;
  67635. }
  67636. return false;
  67637. };
  67638. var logOperation = function (operation, producer) {
  67639. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67640. };
  67641. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67642. if (addToScene === void 0) { addToScene = false; }
  67643. var container = new BABYLON.AssetContainer(scene);
  67644. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67645. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67646. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67647. // and avoid problems with multiple concurrent .babylon loads.
  67648. var log = "importScene has failed JSON parse";
  67649. try {
  67650. var parsedData = JSON.parse(data);
  67651. log = "";
  67652. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67653. var index;
  67654. var cache;
  67655. // Lights
  67656. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67657. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67658. var parsedLight = parsedData.lights[index];
  67659. var light = BABYLON.Light.Parse(parsedLight, scene);
  67660. if (light) {
  67661. container.lights.push(light);
  67662. log += (index === 0 ? "\n\tLights:" : "");
  67663. log += "\n\t\t" + light.toString(fullDetails);
  67664. }
  67665. }
  67666. }
  67667. // Animations
  67668. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67669. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67670. var parsedAnimation = parsedData.animations[index];
  67671. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67672. scene.animations.push(animation);
  67673. container.animations.push(animation);
  67674. log += (index === 0 ? "\n\tAnimations:" : "");
  67675. log += "\n\t\t" + animation.toString(fullDetails);
  67676. }
  67677. }
  67678. // Materials
  67679. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67680. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67681. var parsedMaterial = parsedData.materials[index];
  67682. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67683. container.materials.push(mat);
  67684. log += (index === 0 ? "\n\tMaterials:" : "");
  67685. log += "\n\t\t" + mat.toString(fullDetails);
  67686. }
  67687. }
  67688. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67689. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67690. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67691. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67692. container.multiMaterials.push(mmat);
  67693. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67694. log += "\n\t\t" + mmat.toString(fullDetails);
  67695. }
  67696. }
  67697. // Morph targets
  67698. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67699. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67700. var managerData = _a[_i];
  67701. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67702. }
  67703. }
  67704. // Skeletons
  67705. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67706. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67707. var parsedSkeleton = parsedData.skeletons[index];
  67708. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67709. container.skeletons.push(skeleton);
  67710. log += (index === 0 ? "\n\tSkeletons:" : "");
  67711. log += "\n\t\t" + skeleton.toString(fullDetails);
  67712. }
  67713. }
  67714. // Geometries
  67715. var geometries = parsedData.geometries;
  67716. if (geometries !== undefined && geometries !== null) {
  67717. var addedGeometry = new Array();
  67718. // Boxes
  67719. var boxes = geometries.boxes;
  67720. if (boxes !== undefined && boxes !== null) {
  67721. for (index = 0, cache = boxes.length; index < cache; index++) {
  67722. var parsedBox = boxes[index];
  67723. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67724. }
  67725. }
  67726. // Spheres
  67727. var spheres = geometries.spheres;
  67728. if (spheres !== undefined && spheres !== null) {
  67729. for (index = 0, cache = spheres.length; index < cache; index++) {
  67730. var parsedSphere = spheres[index];
  67731. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67732. }
  67733. }
  67734. // Cylinders
  67735. var cylinders = geometries.cylinders;
  67736. if (cylinders !== undefined && cylinders !== null) {
  67737. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67738. var parsedCylinder = cylinders[index];
  67739. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67740. }
  67741. }
  67742. // Toruses
  67743. var toruses = geometries.toruses;
  67744. if (toruses !== undefined && toruses !== null) {
  67745. for (index = 0, cache = toruses.length; index < cache; index++) {
  67746. var parsedTorus = toruses[index];
  67747. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67748. }
  67749. }
  67750. // Grounds
  67751. var grounds = geometries.grounds;
  67752. if (grounds !== undefined && grounds !== null) {
  67753. for (index = 0, cache = grounds.length; index < cache; index++) {
  67754. var parsedGround = grounds[index];
  67755. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67756. }
  67757. }
  67758. // Planes
  67759. var planes = geometries.planes;
  67760. if (planes !== undefined && planes !== null) {
  67761. for (index = 0, cache = planes.length; index < cache; index++) {
  67762. var parsedPlane = planes[index];
  67763. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67764. }
  67765. }
  67766. // TorusKnots
  67767. var torusKnots = geometries.torusKnots;
  67768. if (torusKnots !== undefined && torusKnots !== null) {
  67769. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67770. var parsedTorusKnot = torusKnots[index];
  67771. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67772. }
  67773. }
  67774. // VertexData
  67775. var vertexData = geometries.vertexData;
  67776. if (vertexData !== undefined && vertexData !== null) {
  67777. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67778. var parsedVertexData = vertexData[index];
  67779. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67780. }
  67781. }
  67782. addedGeometry.forEach(function (g) {
  67783. if (g) {
  67784. container.geometries.push(g);
  67785. }
  67786. });
  67787. }
  67788. // Transform nodes
  67789. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67790. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67791. var parsedTransformNode = parsedData.transformNodes[index];
  67792. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67793. container.transformNodes.push(node);
  67794. }
  67795. }
  67796. // Meshes
  67797. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67798. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67799. var parsedMesh = parsedData.meshes[index];
  67800. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67801. container.meshes.push(mesh);
  67802. log += (index === 0 ? "\n\tMeshes:" : "");
  67803. log += "\n\t\t" + mesh.toString(fullDetails);
  67804. }
  67805. }
  67806. // Cameras
  67807. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67808. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67809. var parsedCamera = parsedData.cameras[index];
  67810. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67811. container.cameras.push(camera);
  67812. log += (index === 0 ? "\n\tCameras:" : "");
  67813. log += "\n\t\t" + camera.toString(fullDetails);
  67814. }
  67815. }
  67816. // Browsing all the graph to connect the dots
  67817. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67818. var camera = scene.cameras[index];
  67819. if (camera._waitingParentId) {
  67820. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67821. camera._waitingParentId = null;
  67822. }
  67823. }
  67824. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67825. var light_1 = scene.lights[index];
  67826. if (light_1 && light_1._waitingParentId) {
  67827. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67828. light_1._waitingParentId = null;
  67829. }
  67830. }
  67831. // Sounds
  67832. // TODO: add sound
  67833. var loadedSounds = [];
  67834. var loadedSound;
  67835. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67836. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67837. var parsedSound = parsedData.sounds[index];
  67838. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67839. if (!parsedSound.url)
  67840. parsedSound.url = parsedSound.name;
  67841. if (!loadedSounds[parsedSound.url]) {
  67842. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67843. loadedSounds[parsedSound.url] = loadedSound;
  67844. container.sounds.push(loadedSound);
  67845. }
  67846. else {
  67847. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67848. }
  67849. }
  67850. else {
  67851. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67852. }
  67853. }
  67854. }
  67855. loadedSounds = [];
  67856. // Connect parents & children and parse actions
  67857. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67858. var transformNode = scene.transformNodes[index];
  67859. if (transformNode._waitingParentId) {
  67860. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67861. transformNode._waitingParentId = null;
  67862. }
  67863. }
  67864. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67865. var mesh = scene.meshes[index];
  67866. if (mesh._waitingParentId) {
  67867. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67868. mesh._waitingParentId = null;
  67869. }
  67870. if (mesh._waitingActions) {
  67871. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67872. mesh._waitingActions = null;
  67873. }
  67874. }
  67875. // freeze world matrix application
  67876. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67877. var currentMesh = scene.meshes[index];
  67878. if (currentMesh._waitingFreezeWorldMatrix) {
  67879. currentMesh.freezeWorldMatrix();
  67880. currentMesh._waitingFreezeWorldMatrix = null;
  67881. }
  67882. else {
  67883. currentMesh.computeWorldMatrix(true);
  67884. }
  67885. }
  67886. // Particles Systems
  67887. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67888. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67889. var parsedParticleSystem = parsedData.particleSystems[index];
  67890. if (parsedParticleSystem.activeParticleCount) {
  67891. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67892. container.particleSystems.push(ps);
  67893. }
  67894. else {
  67895. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67896. container.particleSystems.push(ps);
  67897. }
  67898. }
  67899. }
  67900. // Lens flares
  67901. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67902. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67903. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67904. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67905. container.lensFlareSystems.push(lf);
  67906. }
  67907. }
  67908. // Shadows
  67909. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67910. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67911. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67912. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67913. container.shadowGenerators.push(sg);
  67914. }
  67915. }
  67916. // Lights exclusions / inclusions
  67917. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67918. var light_2 = scene.lights[index];
  67919. // Excluded check
  67920. if (light_2._excludedMeshesIds.length > 0) {
  67921. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67922. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67923. if (excludedMesh) {
  67924. light_2.excludedMeshes.push(excludedMesh);
  67925. }
  67926. }
  67927. light_2._excludedMeshesIds = [];
  67928. }
  67929. // Included check
  67930. if (light_2._includedOnlyMeshesIds.length > 0) {
  67931. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67932. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67933. if (includedOnlyMesh) {
  67934. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67935. }
  67936. }
  67937. light_2._includedOnlyMeshesIds = [];
  67938. }
  67939. }
  67940. // Effect layers
  67941. if (parsedData.effectLayers) {
  67942. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67943. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67944. container.effectLayers.push(effectLayer);
  67945. }
  67946. }
  67947. // Actions (scene)
  67948. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67949. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67950. }
  67951. if (!addToScene) {
  67952. container.removeAllFromScene();
  67953. }
  67954. }
  67955. catch (err) {
  67956. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67957. if (onError) {
  67958. onError(msg, err);
  67959. }
  67960. else {
  67961. BABYLON.Tools.Log(msg);
  67962. throw err;
  67963. }
  67964. }
  67965. finally {
  67966. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67967. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67968. }
  67969. }
  67970. return container;
  67971. };
  67972. BABYLON.SceneLoader.RegisterPlugin({
  67973. name: "babylon.js",
  67974. extensions: ".babylon",
  67975. canDirectLoad: function (data) {
  67976. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67977. return true;
  67978. }
  67979. return false;
  67980. },
  67981. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67982. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67983. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67984. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67985. // and avoid problems with multiple concurrent .babylon loads.
  67986. var log = "importMesh has failed JSON parse";
  67987. try {
  67988. var parsedData = JSON.parse(data);
  67989. log = "";
  67990. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67991. if (!meshesNames) {
  67992. meshesNames = null;
  67993. }
  67994. else if (!Array.isArray(meshesNames)) {
  67995. meshesNames = [meshesNames];
  67996. }
  67997. var hierarchyIds = new Array();
  67998. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67999. var loadedSkeletonsIds = [];
  68000. var loadedMaterialsIds = [];
  68001. var index;
  68002. var cache;
  68003. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68004. var parsedMesh = parsedData.meshes[index];
  68005. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68006. if (meshesNames !== null) {
  68007. // Remove found mesh name from list.
  68008. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68009. }
  68010. //Geometry?
  68011. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68012. //does the file contain geometries?
  68013. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68014. //find the correct geometry and add it to the scene
  68015. var found = false;
  68016. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68017. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68018. return;
  68019. }
  68020. else {
  68021. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68022. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68023. switch (geometryType) {
  68024. case "boxes":
  68025. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68026. break;
  68027. case "spheres":
  68028. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68029. break;
  68030. case "cylinders":
  68031. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68032. break;
  68033. case "toruses":
  68034. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68035. break;
  68036. case "grounds":
  68037. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68038. break;
  68039. case "planes":
  68040. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68041. break;
  68042. case "torusKnots":
  68043. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68044. break;
  68045. case "vertexData":
  68046. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68047. break;
  68048. }
  68049. found = true;
  68050. }
  68051. });
  68052. }
  68053. });
  68054. if (found === false) {
  68055. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68056. }
  68057. }
  68058. }
  68059. // Material ?
  68060. if (parsedMesh.materialId) {
  68061. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68062. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68063. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68064. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68065. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68066. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68067. var subMatId = parsedMultiMaterial.materials[matIndex];
  68068. loadedMaterialsIds.push(subMatId);
  68069. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68070. if (mat) {
  68071. log += "\n\tMaterial " + mat.toString(fullDetails);
  68072. }
  68073. }
  68074. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68075. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68076. if (mmat) {
  68077. materialFound = true;
  68078. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68079. }
  68080. break;
  68081. }
  68082. }
  68083. }
  68084. if (materialFound === false) {
  68085. loadedMaterialsIds.push(parsedMesh.materialId);
  68086. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68087. if (!mat) {
  68088. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68089. }
  68090. else {
  68091. log += "\n\tMaterial " + mat.toString(fullDetails);
  68092. }
  68093. }
  68094. }
  68095. // Skeleton ?
  68096. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68097. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68098. if (skeletonAlreadyLoaded === false) {
  68099. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68100. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68101. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68102. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68103. skeletons.push(skeleton);
  68104. loadedSkeletonsIds.push(parsedSkeleton.id);
  68105. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68106. }
  68107. }
  68108. }
  68109. }
  68110. // Morph targets ?
  68111. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68112. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68113. var managerData = _a[_i];
  68114. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68115. }
  68116. }
  68117. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68118. meshes.push(mesh);
  68119. log += "\n\tMesh " + mesh.toString(fullDetails);
  68120. }
  68121. }
  68122. // Connecting parents
  68123. var currentMesh;
  68124. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68125. currentMesh = scene.meshes[index];
  68126. if (currentMesh._waitingParentId) {
  68127. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68128. currentMesh._waitingParentId = null;
  68129. }
  68130. }
  68131. // freeze and compute world matrix application
  68132. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68133. currentMesh = scene.meshes[index];
  68134. if (currentMesh._waitingFreezeWorldMatrix) {
  68135. currentMesh.freezeWorldMatrix();
  68136. currentMesh._waitingFreezeWorldMatrix = null;
  68137. }
  68138. else {
  68139. currentMesh.computeWorldMatrix(true);
  68140. }
  68141. }
  68142. }
  68143. // Particles
  68144. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68145. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68146. var parsedParticleSystem = parsedData.particleSystems[index];
  68147. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68148. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68149. }
  68150. }
  68151. }
  68152. return true;
  68153. }
  68154. catch (err) {
  68155. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68156. if (onError) {
  68157. onError(msg, err);
  68158. }
  68159. else {
  68160. BABYLON.Tools.Log(msg);
  68161. throw err;
  68162. }
  68163. }
  68164. finally {
  68165. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68166. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68167. }
  68168. }
  68169. return false;
  68170. },
  68171. load: function (scene, data, rootUrl, onError) {
  68172. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68173. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68174. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68175. // and avoid problems with multiple concurrent .babylon loads.
  68176. var log = "importScene has failed JSON parse";
  68177. try {
  68178. var parsedData = JSON.parse(data);
  68179. log = "";
  68180. // Scene
  68181. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68182. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68183. }
  68184. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68185. scene.autoClear = parsedData.autoClear;
  68186. }
  68187. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68188. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68189. }
  68190. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68191. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68192. }
  68193. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68194. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68195. }
  68196. // Fog
  68197. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68198. scene.fogMode = parsedData.fogMode;
  68199. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68200. scene.fogStart = parsedData.fogStart;
  68201. scene.fogEnd = parsedData.fogEnd;
  68202. scene.fogDensity = parsedData.fogDensity;
  68203. log += "\tFog mode for scene: ";
  68204. switch (scene.fogMode) {
  68205. // getters not compiling, so using hardcoded
  68206. case 1:
  68207. log += "exp\n";
  68208. break;
  68209. case 2:
  68210. log += "exp2\n";
  68211. break;
  68212. case 3:
  68213. log += "linear\n";
  68214. break;
  68215. }
  68216. }
  68217. //Physics
  68218. if (parsedData.physicsEnabled) {
  68219. var physicsPlugin;
  68220. if (parsedData.physicsEngine === "cannon") {
  68221. physicsPlugin = new BABYLON.CannonJSPlugin();
  68222. }
  68223. else if (parsedData.physicsEngine === "oimo") {
  68224. physicsPlugin = new BABYLON.OimoJSPlugin();
  68225. }
  68226. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68227. //else - default engine, which is currently oimo
  68228. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68229. scene.enablePhysics(physicsGravity, physicsPlugin);
  68230. }
  68231. // Metadata
  68232. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68233. scene.metadata = parsedData.metadata;
  68234. }
  68235. //collisions, if defined. otherwise, default is true
  68236. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68237. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68238. }
  68239. scene.workerCollisions = !!parsedData.workerCollisions;
  68240. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68241. if (!container) {
  68242. return false;
  68243. }
  68244. if (parsedData.autoAnimate) {
  68245. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68246. }
  68247. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68248. scene.setActiveCameraByID(parsedData.activeCameraID);
  68249. }
  68250. // Environment texture
  68251. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68252. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68253. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68254. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68255. if (parsedData.environmentTextureRotationY) {
  68256. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68257. }
  68258. scene.environmentTexture = hdrTexture;
  68259. }
  68260. else {
  68261. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68262. if (parsedData.environmentTextureRotationY) {
  68263. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68264. }
  68265. scene.environmentTexture = cubeTexture;
  68266. }
  68267. if (parsedData.createDefaultSkybox === true) {
  68268. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68269. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68270. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68271. }
  68272. }
  68273. // Finish
  68274. return true;
  68275. }
  68276. catch (err) {
  68277. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68278. if (onError) {
  68279. onError(msg, err);
  68280. }
  68281. else {
  68282. BABYLON.Tools.Log(msg);
  68283. throw err;
  68284. }
  68285. }
  68286. finally {
  68287. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68288. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68289. }
  68290. }
  68291. return false;
  68292. },
  68293. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68294. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68295. return container;
  68296. }
  68297. });
  68298. })(BABYLON || (BABYLON = {}));
  68299. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68300. var BABYLON;
  68301. (function (BABYLON) {
  68302. var FilesInput = /** @class */ (function () {
  68303. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68304. this.onProcessFileCallback = function () { return true; };
  68305. this._engine = engine;
  68306. this._currentScene = scene;
  68307. this._sceneLoadedCallback = sceneLoadedCallback;
  68308. this._progressCallback = progressCallback;
  68309. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68310. this._textureLoadingCallback = textureLoadingCallback;
  68311. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68312. this._onReloadCallback = onReloadCallback;
  68313. this._errorCallback = errorCallback;
  68314. }
  68315. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68316. var _this = this;
  68317. if (elementToMonitor) {
  68318. this._elementToMonitor = elementToMonitor;
  68319. this._dragEnterHandler = function (e) { _this.drag(e); };
  68320. this._dragOverHandler = function (e) { _this.drag(e); };
  68321. this._dropHandler = function (e) { _this.drop(e); };
  68322. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68323. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68324. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68325. }
  68326. };
  68327. FilesInput.prototype.dispose = function () {
  68328. if (!this._elementToMonitor) {
  68329. return;
  68330. }
  68331. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68332. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68333. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68334. };
  68335. FilesInput.prototype.renderFunction = function () {
  68336. if (this._additionalRenderLoopLogicCallback) {
  68337. this._additionalRenderLoopLogicCallback();
  68338. }
  68339. if (this._currentScene) {
  68340. if (this._textureLoadingCallback) {
  68341. var remaining = this._currentScene.getWaitingItemsCount();
  68342. if (remaining > 0) {
  68343. this._textureLoadingCallback(remaining);
  68344. }
  68345. }
  68346. this._currentScene.render();
  68347. }
  68348. };
  68349. FilesInput.prototype.drag = function (e) {
  68350. e.stopPropagation();
  68351. e.preventDefault();
  68352. };
  68353. FilesInput.prototype.drop = function (eventDrop) {
  68354. eventDrop.stopPropagation();
  68355. eventDrop.preventDefault();
  68356. this.loadFiles(eventDrop);
  68357. };
  68358. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68359. var _this = this;
  68360. var reader = folder.createReader();
  68361. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68362. reader.readEntries(function (entries) {
  68363. remaining.count += entries.length;
  68364. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68365. var entry = entries_1[_i];
  68366. if (entry.isFile) {
  68367. entry.file(function (file) {
  68368. file.correctName = relativePath + file.name;
  68369. files.push(file);
  68370. if (--remaining.count === 0) {
  68371. callback();
  68372. }
  68373. });
  68374. }
  68375. else if (entry.isDirectory) {
  68376. _this._traverseFolder(entry, files, remaining, callback);
  68377. }
  68378. }
  68379. if (--remaining.count) {
  68380. callback();
  68381. }
  68382. });
  68383. };
  68384. FilesInput.prototype._processFiles = function (files) {
  68385. for (var i = 0; i < files.length; i++) {
  68386. var name = files[i].correctName.toLowerCase();
  68387. var extension = name.split('.').pop();
  68388. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68389. continue;
  68390. }
  68391. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68392. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68393. this._sceneFileToLoad = files[i];
  68394. }
  68395. else {
  68396. FilesInput.FilesToLoad[name] = files[i];
  68397. }
  68398. }
  68399. };
  68400. FilesInput.prototype.loadFiles = function (event) {
  68401. var _this = this;
  68402. if (this._startingProcessingFilesCallback)
  68403. this._startingProcessingFilesCallback();
  68404. // Handling data transfer via drag'n'drop
  68405. if (event && event.dataTransfer && event.dataTransfer.files) {
  68406. this._filesToLoad = event.dataTransfer.files;
  68407. }
  68408. // Handling files from input files
  68409. if (event && event.target && event.target.files) {
  68410. this._filesToLoad = event.target.files;
  68411. }
  68412. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68413. var files_1 = new Array();
  68414. var folders = [];
  68415. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68416. for (var i = 0; i < this._filesToLoad.length; i++) {
  68417. var fileToLoad = this._filesToLoad[i];
  68418. var name_1 = fileToLoad.name.toLowerCase();
  68419. var entry = void 0;
  68420. fileToLoad.correctName = name_1;
  68421. if (items) {
  68422. var item = items[i];
  68423. if (item.getAsEntry) {
  68424. entry = item.getAsEntry();
  68425. }
  68426. else if (item.webkitGetAsEntry) {
  68427. entry = item.webkitGetAsEntry();
  68428. }
  68429. }
  68430. if (!entry) {
  68431. files_1.push(fileToLoad);
  68432. }
  68433. else {
  68434. if (entry.isDirectory) {
  68435. folders.push(entry);
  68436. }
  68437. else {
  68438. files_1.push(fileToLoad);
  68439. }
  68440. }
  68441. }
  68442. if (folders.length === 0) {
  68443. this._processFiles(files_1);
  68444. this._processReload();
  68445. }
  68446. else {
  68447. var remaining = { count: folders.length };
  68448. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68449. var folder = folders_1[_i];
  68450. this._traverseFolder(folder, files_1, remaining, function () {
  68451. _this._processFiles(files_1);
  68452. if (remaining.count === 0) {
  68453. _this._processReload();
  68454. }
  68455. });
  68456. }
  68457. }
  68458. }
  68459. };
  68460. FilesInput.prototype._processReload = function () {
  68461. if (this._onReloadCallback) {
  68462. this._onReloadCallback(this._sceneFileToLoad);
  68463. }
  68464. else {
  68465. this.reload();
  68466. }
  68467. };
  68468. FilesInput.prototype.reload = function () {
  68469. var _this = this;
  68470. // If a scene file has been provided
  68471. if (this._sceneFileToLoad) {
  68472. if (this._currentScene) {
  68473. if (BABYLON.Tools.errorsCount > 0) {
  68474. BABYLON.Tools.ClearLogCache();
  68475. }
  68476. this._engine.stopRenderLoop();
  68477. }
  68478. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68479. if (_this._progressCallback) {
  68480. _this._progressCallback(progress);
  68481. }
  68482. }).then(function (scene) {
  68483. if (_this._currentScene) {
  68484. _this._currentScene.dispose();
  68485. }
  68486. _this._currentScene = scene;
  68487. if (_this._sceneLoadedCallback) {
  68488. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68489. }
  68490. // Wait for textures and shaders to be ready
  68491. _this._currentScene.executeWhenReady(function () {
  68492. _this._engine.runRenderLoop(function () {
  68493. _this.renderFunction();
  68494. });
  68495. });
  68496. }).catch(function (error) {
  68497. if (_this._errorCallback) {
  68498. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68499. }
  68500. });
  68501. }
  68502. else {
  68503. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68504. }
  68505. };
  68506. FilesInput.FilesToLoad = {};
  68507. return FilesInput;
  68508. }());
  68509. BABYLON.FilesInput = FilesInput;
  68510. })(BABYLON || (BABYLON = {}));
  68511. //# sourceMappingURL=babylon.filesInput.js.map
  68512. var BABYLON;
  68513. (function (BABYLON) {
  68514. /**
  68515. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68516. * The underlying implementation relies on an associative array to ensure the best performances.
  68517. * The value can be anything including 'null' but except 'undefined'
  68518. */
  68519. var StringDictionary = /** @class */ (function () {
  68520. function StringDictionary() {
  68521. this._count = 0;
  68522. this._data = {};
  68523. }
  68524. /**
  68525. * This will clear this dictionary and copy the content from the 'source' one.
  68526. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68527. * @param source the dictionary to take the content from and copy to this dictionary
  68528. */
  68529. StringDictionary.prototype.copyFrom = function (source) {
  68530. var _this = this;
  68531. this.clear();
  68532. source.forEach(function (t, v) { return _this.add(t, v); });
  68533. };
  68534. /**
  68535. * Get a value based from its key
  68536. * @param key the given key to get the matching value from
  68537. * @return the value if found, otherwise undefined is returned
  68538. */
  68539. StringDictionary.prototype.get = function (key) {
  68540. var val = this._data[key];
  68541. if (val !== undefined) {
  68542. return val;
  68543. }
  68544. return undefined;
  68545. };
  68546. /**
  68547. * Get a value from its key or add it if it doesn't exist.
  68548. * This method will ensure you that a given key/data will be present in the dictionary.
  68549. * @param key the given key to get the matching value from
  68550. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68551. * The factory will only be invoked if there's no data for the given key.
  68552. * @return the value corresponding to the key.
  68553. */
  68554. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68555. var val = this.get(key);
  68556. if (val !== undefined) {
  68557. return val;
  68558. }
  68559. val = factory(key);
  68560. if (val) {
  68561. this.add(key, val);
  68562. }
  68563. return val;
  68564. };
  68565. /**
  68566. * Get a value from its key if present in the dictionary otherwise add it
  68567. * @param key the key to get the value from
  68568. * @param val if there's no such key/value pair in the dictionary add it with this value
  68569. * @return the value corresponding to the key
  68570. */
  68571. StringDictionary.prototype.getOrAdd = function (key, val) {
  68572. var curVal = this.get(key);
  68573. if (curVal !== undefined) {
  68574. return curVal;
  68575. }
  68576. this.add(key, val);
  68577. return val;
  68578. };
  68579. /**
  68580. * Check if there's a given key in the dictionary
  68581. * @param key the key to check for
  68582. * @return true if the key is present, false otherwise
  68583. */
  68584. StringDictionary.prototype.contains = function (key) {
  68585. return this._data[key] !== undefined;
  68586. };
  68587. /**
  68588. * Add a new key and its corresponding value
  68589. * @param key the key to add
  68590. * @param value the value corresponding to the key
  68591. * @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
  68592. */
  68593. StringDictionary.prototype.add = function (key, value) {
  68594. if (this._data[key] !== undefined) {
  68595. return false;
  68596. }
  68597. this._data[key] = value;
  68598. ++this._count;
  68599. return true;
  68600. };
  68601. StringDictionary.prototype.set = function (key, value) {
  68602. if (this._data[key] === undefined) {
  68603. return false;
  68604. }
  68605. this._data[key] = value;
  68606. return true;
  68607. };
  68608. /**
  68609. * Get the element of the given key and remove it from the dictionary
  68610. * @param key
  68611. */
  68612. StringDictionary.prototype.getAndRemove = function (key) {
  68613. var val = this.get(key);
  68614. if (val !== undefined) {
  68615. delete this._data[key];
  68616. --this._count;
  68617. return val;
  68618. }
  68619. return null;
  68620. };
  68621. /**
  68622. * Remove a key/value from the dictionary.
  68623. * @param key the key to remove
  68624. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68625. */
  68626. StringDictionary.prototype.remove = function (key) {
  68627. if (this.contains(key)) {
  68628. delete this._data[key];
  68629. --this._count;
  68630. return true;
  68631. }
  68632. return false;
  68633. };
  68634. /**
  68635. * Clear the whole content of the dictionary
  68636. */
  68637. StringDictionary.prototype.clear = function () {
  68638. this._data = {};
  68639. this._count = 0;
  68640. };
  68641. Object.defineProperty(StringDictionary.prototype, "count", {
  68642. get: function () {
  68643. return this._count;
  68644. },
  68645. enumerable: true,
  68646. configurable: true
  68647. });
  68648. /**
  68649. * Execute a callback on each key/val of the dictionary.
  68650. * Note that you can remove any element in this dictionary in the callback implementation
  68651. * @param callback the callback to execute on a given key/value pair
  68652. */
  68653. StringDictionary.prototype.forEach = function (callback) {
  68654. for (var cur in this._data) {
  68655. var val = this._data[cur];
  68656. callback(cur, val);
  68657. }
  68658. };
  68659. /**
  68660. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68661. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68662. * Note that you can remove any element in this dictionary in the callback implementation
  68663. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68664. */
  68665. StringDictionary.prototype.first = function (callback) {
  68666. for (var cur in this._data) {
  68667. var val = this._data[cur];
  68668. var res = callback(cur, val);
  68669. if (res) {
  68670. return res;
  68671. }
  68672. }
  68673. return null;
  68674. };
  68675. return StringDictionary;
  68676. }());
  68677. BABYLON.StringDictionary = StringDictionary;
  68678. })(BABYLON || (BABYLON = {}));
  68679. //# sourceMappingURL=babylon.stringDictionary.js.map
  68680. var BABYLON;
  68681. (function (BABYLON) {
  68682. var Tags = /** @class */ (function () {
  68683. function Tags() {
  68684. }
  68685. Tags.EnableFor = function (obj) {
  68686. obj._tags = obj._tags || {};
  68687. obj.hasTags = function () {
  68688. return Tags.HasTags(obj);
  68689. };
  68690. obj.addTags = function (tagsString) {
  68691. return Tags.AddTagsTo(obj, tagsString);
  68692. };
  68693. obj.removeTags = function (tagsString) {
  68694. return Tags.RemoveTagsFrom(obj, tagsString);
  68695. };
  68696. obj.matchesTagsQuery = function (tagsQuery) {
  68697. return Tags.MatchesQuery(obj, tagsQuery);
  68698. };
  68699. };
  68700. Tags.DisableFor = function (obj) {
  68701. delete obj._tags;
  68702. delete obj.hasTags;
  68703. delete obj.addTags;
  68704. delete obj.removeTags;
  68705. delete obj.matchesTagsQuery;
  68706. };
  68707. Tags.HasTags = function (obj) {
  68708. if (!obj._tags) {
  68709. return false;
  68710. }
  68711. return !BABYLON.Tools.IsEmpty(obj._tags);
  68712. };
  68713. Tags.GetTags = function (obj, asString) {
  68714. if (asString === void 0) { asString = true; }
  68715. if (!obj._tags) {
  68716. return null;
  68717. }
  68718. if (asString) {
  68719. var tagsArray = [];
  68720. for (var tag in obj._tags) {
  68721. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68722. tagsArray.push(tag);
  68723. }
  68724. }
  68725. return tagsArray.join(" ");
  68726. }
  68727. else {
  68728. return obj._tags;
  68729. }
  68730. };
  68731. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68732. // a tag cannot start with '||', '&&', and '!'
  68733. // it cannot contain whitespaces
  68734. Tags.AddTagsTo = function (obj, tagsString) {
  68735. if (!tagsString) {
  68736. return;
  68737. }
  68738. if (typeof tagsString !== "string") {
  68739. return;
  68740. }
  68741. var tags = tagsString.split(" ");
  68742. tags.forEach(function (tag, index, array) {
  68743. Tags._AddTagTo(obj, tag);
  68744. });
  68745. };
  68746. Tags._AddTagTo = function (obj, tag) {
  68747. tag = tag.trim();
  68748. if (tag === "" || tag === "true" || tag === "false") {
  68749. return;
  68750. }
  68751. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68752. return;
  68753. }
  68754. Tags.EnableFor(obj);
  68755. obj._tags[tag] = true;
  68756. };
  68757. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68758. if (!Tags.HasTags(obj)) {
  68759. return;
  68760. }
  68761. var tags = tagsString.split(" ");
  68762. for (var t in tags) {
  68763. Tags._RemoveTagFrom(obj, tags[t]);
  68764. }
  68765. };
  68766. Tags._RemoveTagFrom = function (obj, tag) {
  68767. delete obj._tags[tag];
  68768. };
  68769. Tags.MatchesQuery = function (obj, tagsQuery) {
  68770. if (tagsQuery === undefined) {
  68771. return true;
  68772. }
  68773. if (tagsQuery === "") {
  68774. return Tags.HasTags(obj);
  68775. }
  68776. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68777. };
  68778. return Tags;
  68779. }());
  68780. BABYLON.Tags = Tags;
  68781. })(BABYLON || (BABYLON = {}));
  68782. //# sourceMappingURL=babylon.tags.js.map
  68783. var BABYLON;
  68784. (function (BABYLON) {
  68785. /**
  68786. * Class used to evalaute queries containing `and` and `or` operators
  68787. */
  68788. var AndOrNotEvaluator = /** @class */ (function () {
  68789. function AndOrNotEvaluator() {
  68790. }
  68791. /**
  68792. * Evaluate a query
  68793. * @param query defines the query to evaluate
  68794. * @param evaluateCallback defines the callback used to filter result
  68795. * @returns true if the query matches
  68796. */
  68797. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68798. if (!query.match(/\([^\(\)]*\)/g)) {
  68799. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68800. }
  68801. else {
  68802. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68803. // remove parenthesis
  68804. r = r.slice(1, r.length - 1);
  68805. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68806. });
  68807. }
  68808. if (query === "true") {
  68809. return true;
  68810. }
  68811. if (query === "false") {
  68812. return false;
  68813. }
  68814. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68815. };
  68816. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68817. evaluateCallback = evaluateCallback || (function (r) {
  68818. return r === "true" ? true : false;
  68819. });
  68820. var result;
  68821. var or = parenthesisContent.split("||");
  68822. for (var i in or) {
  68823. if (or.hasOwnProperty(i)) {
  68824. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68825. var and = ori.split("&&");
  68826. if (and.length > 1) {
  68827. for (var j = 0; j < and.length; ++j) {
  68828. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68829. if (andj !== "true" && andj !== "false") {
  68830. if (andj[0] === "!") {
  68831. result = !evaluateCallback(andj.substring(1));
  68832. }
  68833. else {
  68834. result = evaluateCallback(andj);
  68835. }
  68836. }
  68837. else {
  68838. result = andj === "true" ? true : false;
  68839. }
  68840. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68841. ori = "false";
  68842. break;
  68843. }
  68844. }
  68845. }
  68846. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68847. result = true;
  68848. break;
  68849. }
  68850. // result equals false (or undefined)
  68851. if (ori !== "true" && ori !== "false") {
  68852. if (ori[0] === "!") {
  68853. result = !evaluateCallback(ori.substring(1));
  68854. }
  68855. else {
  68856. result = evaluateCallback(ori);
  68857. }
  68858. }
  68859. else {
  68860. result = ori === "true" ? true : false;
  68861. }
  68862. }
  68863. }
  68864. // the whole parenthesis scope is replaced by 'true' or 'false'
  68865. return result ? "true" : "false";
  68866. };
  68867. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68868. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68869. // remove whitespaces
  68870. r = r.replace(/[\s]/g, function () { return ""; });
  68871. return r.length % 2 ? "!" : "";
  68872. });
  68873. booleanString = booleanString.trim();
  68874. if (booleanString === "!true") {
  68875. booleanString = "false";
  68876. }
  68877. else if (booleanString === "!false") {
  68878. booleanString = "true";
  68879. }
  68880. return booleanString;
  68881. };
  68882. return AndOrNotEvaluator;
  68883. }());
  68884. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68885. })(BABYLON || (BABYLON = {}));
  68886. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68887. var BABYLON;
  68888. (function (BABYLON) {
  68889. /**
  68890. * Class used to enable access to IndexedDB
  68891. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68892. */
  68893. var Database = /** @class */ (function () {
  68894. /**
  68895. * Creates a new Database
  68896. * @param urlToScene defines the url to load the scene
  68897. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68898. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68899. */
  68900. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68901. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68902. var _this = this;
  68903. // Handling various flavors of prefixed version of IndexedDB
  68904. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68905. this.callbackManifestChecked = callbackManifestChecked;
  68906. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68907. this.db = null;
  68908. this._enableSceneOffline = false;
  68909. this._enableTexturesOffline = false;
  68910. this.manifestVersionFound = 0;
  68911. this.mustUpdateRessources = false;
  68912. this.hasReachedQuota = false;
  68913. if (!Database.IDBStorageEnabled) {
  68914. this.callbackManifestChecked(true);
  68915. }
  68916. else {
  68917. if (disableManifestCheck) {
  68918. this._enableSceneOffline = true;
  68919. this._enableTexturesOffline = true;
  68920. this.manifestVersionFound = 1;
  68921. BABYLON.Tools.SetImmediate(function () {
  68922. _this.callbackManifestChecked(true);
  68923. });
  68924. }
  68925. else {
  68926. this._checkManifestFile();
  68927. }
  68928. }
  68929. }
  68930. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68931. /**
  68932. * Gets a boolean indicating if scene must be saved in the database
  68933. */
  68934. get: function () {
  68935. return this._enableSceneOffline;
  68936. },
  68937. enumerable: true,
  68938. configurable: true
  68939. });
  68940. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68941. /**
  68942. * Gets a boolean indicating if textures must be saved in the database
  68943. */
  68944. get: function () {
  68945. return this._enableTexturesOffline;
  68946. },
  68947. enumerable: true,
  68948. configurable: true
  68949. });
  68950. Database.prototype._checkManifestFile = function () {
  68951. var _this = this;
  68952. var noManifestFile = function () {
  68953. _this._enableSceneOffline = false;
  68954. _this._enableTexturesOffline = false;
  68955. _this.callbackManifestChecked(false);
  68956. };
  68957. var timeStampUsed = false;
  68958. var manifestURL = this.currentSceneUrl + ".manifest";
  68959. var xhr = new XMLHttpRequest();
  68960. if (navigator.onLine) {
  68961. // Adding a timestamp to by-pass browsers' cache
  68962. timeStampUsed = true;
  68963. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68964. }
  68965. xhr.open("GET", manifestURL, true);
  68966. xhr.addEventListener("load", function () {
  68967. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68968. try {
  68969. var manifestFile = JSON.parse(xhr.response);
  68970. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68971. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68972. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68973. _this.manifestVersionFound = manifestFile.version;
  68974. }
  68975. if (_this.callbackManifestChecked) {
  68976. _this.callbackManifestChecked(true);
  68977. }
  68978. }
  68979. catch (ex) {
  68980. noManifestFile();
  68981. }
  68982. }
  68983. else {
  68984. noManifestFile();
  68985. }
  68986. }, false);
  68987. xhr.addEventListener("error", function (event) {
  68988. if (timeStampUsed) {
  68989. timeStampUsed = false;
  68990. // Let's retry without the timeStamp
  68991. // It could fail when coupled with HTML5 Offline API
  68992. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68993. xhr.open("GET", retryManifestURL, true);
  68994. xhr.send();
  68995. }
  68996. else {
  68997. noManifestFile();
  68998. }
  68999. }, false);
  69000. try {
  69001. xhr.send();
  69002. }
  69003. catch (ex) {
  69004. BABYLON.Tools.Error("Error on XHR send request.");
  69005. this.callbackManifestChecked(false);
  69006. }
  69007. };
  69008. /**
  69009. * Open the database and make it available
  69010. * @param successCallback defines the callback to call on success
  69011. * @param errorCallback defines the callback to call on error
  69012. */
  69013. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69014. var _this = this;
  69015. var handleError = function () {
  69016. _this.isSupported = false;
  69017. if (errorCallback)
  69018. errorCallback();
  69019. };
  69020. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69021. // Your browser doesn't support IndexedDB
  69022. this.isSupported = false;
  69023. if (errorCallback)
  69024. errorCallback();
  69025. }
  69026. else {
  69027. // If the DB hasn't been opened or created yet
  69028. if (!this.db) {
  69029. this.hasReachedQuota = false;
  69030. this.isSupported = true;
  69031. var request = this.idbFactory.open("babylonjs", 1);
  69032. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69033. request.onerror = function (event) {
  69034. handleError();
  69035. };
  69036. // executes when a version change transaction cannot complete due to other active transactions
  69037. request.onblocked = function (event) {
  69038. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69039. handleError();
  69040. };
  69041. // DB has been opened successfully
  69042. request.onsuccess = function (event) {
  69043. _this.db = request.result;
  69044. successCallback();
  69045. };
  69046. // Initialization of the DB. Creating Scenes & Textures stores
  69047. request.onupgradeneeded = function (event) {
  69048. _this.db = (event.target).result;
  69049. if (_this.db) {
  69050. try {
  69051. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69052. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69053. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69054. }
  69055. catch (ex) {
  69056. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69057. handleError();
  69058. }
  69059. }
  69060. };
  69061. }
  69062. // DB has already been created and opened
  69063. else {
  69064. if (successCallback)
  69065. successCallback();
  69066. }
  69067. }
  69068. };
  69069. /**
  69070. * Loads an image from the database
  69071. * @param url defines the url to load from
  69072. * @param image defines the target DOM image
  69073. */
  69074. Database.prototype.loadImageFromDB = function (url, image) {
  69075. var _this = this;
  69076. var completeURL = Database._ReturnFullUrlLocation(url);
  69077. var saveAndLoadImage = function () {
  69078. if (!_this.hasReachedQuota && _this.db !== null) {
  69079. // the texture is not yet in the DB, let's try to save it
  69080. _this._saveImageIntoDBAsync(completeURL, image);
  69081. }
  69082. // If the texture is not in the DB and we've reached the DB quota limit
  69083. // let's load it directly from the web
  69084. else {
  69085. image.src = url;
  69086. }
  69087. };
  69088. if (!this.mustUpdateRessources) {
  69089. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69090. }
  69091. // First time we're download the images or update requested in the manifest file by a version change
  69092. else {
  69093. saveAndLoadImage();
  69094. }
  69095. };
  69096. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69097. if (this.isSupported && this.db !== null) {
  69098. var texture;
  69099. var transaction = this.db.transaction(["textures"]);
  69100. transaction.onabort = function (event) {
  69101. image.src = url;
  69102. };
  69103. transaction.oncomplete = function (event) {
  69104. var blobTextureURL;
  69105. if (texture) {
  69106. var URL = window.URL || window.webkitURL;
  69107. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69108. image.onerror = function () {
  69109. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69110. image.src = url;
  69111. };
  69112. image.src = blobTextureURL;
  69113. }
  69114. else {
  69115. notInDBCallback();
  69116. }
  69117. };
  69118. var getRequest = transaction.objectStore("textures").get(url);
  69119. getRequest.onsuccess = function (event) {
  69120. texture = (event.target).result;
  69121. };
  69122. getRequest.onerror = function (event) {
  69123. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69124. image.src = url;
  69125. };
  69126. }
  69127. else {
  69128. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69129. image.src = url;
  69130. }
  69131. };
  69132. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69133. var _this = this;
  69134. if (this.isSupported) {
  69135. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69136. var generateBlobUrl = function () {
  69137. var blobTextureURL;
  69138. if (blob) {
  69139. var URL = window.URL || window.webkitURL;
  69140. try {
  69141. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69142. }
  69143. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69144. catch (ex) {
  69145. blobTextureURL = URL.createObjectURL(blob);
  69146. }
  69147. }
  69148. if (blobTextureURL) {
  69149. image.src = blobTextureURL;
  69150. }
  69151. };
  69152. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69153. var xhr = new XMLHttpRequest(), blob;
  69154. xhr.open("GET", url, true);
  69155. xhr.responseType = "blob";
  69156. xhr.addEventListener("load", function () {
  69157. if (xhr.status === 200 && _this.db) {
  69158. // Blob as response (XHR2)
  69159. blob = xhr.response;
  69160. var transaction = _this.db.transaction(["textures"], "readwrite");
  69161. // the transaction could abort because of a QuotaExceededError error
  69162. transaction.onabort = function (event) {
  69163. try {
  69164. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69165. var srcElement = (event.srcElement || event.target);
  69166. var error = srcElement.error;
  69167. if (error && error.name === "QuotaExceededError") {
  69168. _this.hasReachedQuota = true;
  69169. }
  69170. }
  69171. catch (ex) { }
  69172. generateBlobUrl();
  69173. };
  69174. transaction.oncomplete = function (event) {
  69175. generateBlobUrl();
  69176. };
  69177. var newTexture = { textureUrl: url, data: blob };
  69178. try {
  69179. // Put the blob into the dabase
  69180. var addRequest = transaction.objectStore("textures").put(newTexture);
  69181. addRequest.onsuccess = function (event) {
  69182. };
  69183. addRequest.onerror = function (event) {
  69184. generateBlobUrl();
  69185. };
  69186. }
  69187. catch (ex) {
  69188. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69189. if (ex.code === 25) {
  69190. Database.IsUASupportingBlobStorage = false;
  69191. }
  69192. image.src = url;
  69193. }
  69194. }
  69195. else {
  69196. image.src = url;
  69197. }
  69198. }, false);
  69199. xhr.addEventListener("error", function (event) {
  69200. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69201. image.src = url;
  69202. }, false);
  69203. xhr.send();
  69204. }
  69205. else {
  69206. image.src = url;
  69207. }
  69208. }
  69209. else {
  69210. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69211. image.src = url;
  69212. }
  69213. };
  69214. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69215. var _this = this;
  69216. var updateVersion = function () {
  69217. // the version is not yet in the DB or we need to update it
  69218. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69219. };
  69220. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69221. };
  69222. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69223. var _this = this;
  69224. if (this.isSupported && this.db) {
  69225. var version;
  69226. try {
  69227. var transaction = this.db.transaction(["versions"]);
  69228. transaction.oncomplete = function (event) {
  69229. if (version) {
  69230. // If the version in the JSON file is different from the version in DB
  69231. if (_this.manifestVersionFound !== version.data) {
  69232. _this.mustUpdateRessources = true;
  69233. updateInDBCallback();
  69234. }
  69235. else {
  69236. callback(version.data);
  69237. }
  69238. }
  69239. // version was not found in DB
  69240. else {
  69241. _this.mustUpdateRessources = true;
  69242. updateInDBCallback();
  69243. }
  69244. };
  69245. transaction.onabort = function (event) {
  69246. callback(-1);
  69247. };
  69248. var getRequest = transaction.objectStore("versions").get(url);
  69249. getRequest.onsuccess = function (event) {
  69250. version = (event.target).result;
  69251. };
  69252. getRequest.onerror = function (event) {
  69253. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69254. callback(-1);
  69255. };
  69256. }
  69257. catch (ex) {
  69258. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69259. callback(-1);
  69260. }
  69261. }
  69262. else {
  69263. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69264. callback(-1);
  69265. }
  69266. };
  69267. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69268. var _this = this;
  69269. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69270. try {
  69271. // Open a transaction to the database
  69272. var transaction = this.db.transaction(["versions"], "readwrite");
  69273. // the transaction could abort because of a QuotaExceededError error
  69274. transaction.onabort = function (event) {
  69275. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69276. var error = event.srcElement['error'];
  69277. if (error && error.name === "QuotaExceededError") {
  69278. _this.hasReachedQuota = true;
  69279. }
  69280. }
  69281. catch (ex) { }
  69282. callback(-1);
  69283. };
  69284. transaction.oncomplete = function (event) {
  69285. callback(_this.manifestVersionFound);
  69286. };
  69287. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69288. // Put the scene into the database
  69289. var addRequest = transaction.objectStore("versions").put(newVersion);
  69290. addRequest.onsuccess = function (event) {
  69291. };
  69292. addRequest.onerror = function (event) {
  69293. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69294. };
  69295. }
  69296. catch (ex) {
  69297. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69298. callback(-1);
  69299. }
  69300. }
  69301. else {
  69302. callback(-1);
  69303. }
  69304. };
  69305. /**
  69306. * Loads a file from database
  69307. * @param url defines the URL to load from
  69308. * @param sceneLoaded defines a callback to call on success
  69309. * @param progressCallBack defines a callback to call when progress changed
  69310. * @param errorCallback defines a callback to call on error
  69311. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69312. */
  69313. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69314. var _this = this;
  69315. var completeUrl = Database._ReturnFullUrlLocation(url);
  69316. var saveAndLoadFile = function () {
  69317. // the scene is not yet in the DB, let's try to save it
  69318. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69319. };
  69320. this._checkVersionFromDB(completeUrl, function (version) {
  69321. if (version !== -1) {
  69322. if (!_this.mustUpdateRessources) {
  69323. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69324. }
  69325. else {
  69326. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69327. }
  69328. }
  69329. else {
  69330. if (errorCallback) {
  69331. errorCallback();
  69332. }
  69333. }
  69334. });
  69335. };
  69336. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69337. if (this.isSupported && this.db) {
  69338. var targetStore;
  69339. if (url.indexOf(".babylon") !== -1) {
  69340. targetStore = "scenes";
  69341. }
  69342. else {
  69343. targetStore = "textures";
  69344. }
  69345. var file;
  69346. var transaction = this.db.transaction([targetStore]);
  69347. transaction.oncomplete = function (event) {
  69348. if (file) {
  69349. callback(file.data);
  69350. }
  69351. // file was not found in DB
  69352. else {
  69353. notInDBCallback();
  69354. }
  69355. };
  69356. transaction.onabort = function (event) {
  69357. notInDBCallback();
  69358. };
  69359. var getRequest = transaction.objectStore(targetStore).get(url);
  69360. getRequest.onsuccess = function (event) {
  69361. file = (event.target).result;
  69362. };
  69363. getRequest.onerror = function (event) {
  69364. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69365. notInDBCallback();
  69366. };
  69367. }
  69368. else {
  69369. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69370. callback();
  69371. }
  69372. };
  69373. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69374. var _this = this;
  69375. if (this.isSupported) {
  69376. var targetStore;
  69377. if (url.indexOf(".babylon") !== -1) {
  69378. targetStore = "scenes";
  69379. }
  69380. else {
  69381. targetStore = "textures";
  69382. }
  69383. // Create XHR
  69384. var xhr = new XMLHttpRequest();
  69385. var fileData;
  69386. xhr.open("GET", url, true);
  69387. if (useArrayBuffer) {
  69388. xhr.responseType = "arraybuffer";
  69389. }
  69390. if (progressCallback) {
  69391. xhr.onprogress = progressCallback;
  69392. }
  69393. xhr.addEventListener("load", function () {
  69394. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69395. // Blob as response (XHR2)
  69396. //fileData = xhr.responseText;
  69397. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69398. if (!_this.hasReachedQuota && _this.db) {
  69399. // Open a transaction to the database
  69400. var transaction = _this.db.transaction([targetStore], "readwrite");
  69401. // the transaction could abort because of a QuotaExceededError error
  69402. transaction.onabort = function (event) {
  69403. try {
  69404. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69405. var error = event.srcElement['error'];
  69406. if (error && error.name === "QuotaExceededError") {
  69407. _this.hasReachedQuota = true;
  69408. }
  69409. }
  69410. catch (ex) { }
  69411. callback(fileData);
  69412. };
  69413. transaction.oncomplete = function (event) {
  69414. callback(fileData);
  69415. };
  69416. var newFile;
  69417. if (targetStore === "scenes") {
  69418. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69419. }
  69420. else {
  69421. newFile = { textureUrl: url, data: fileData };
  69422. }
  69423. try {
  69424. // Put the scene into the database
  69425. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69426. addRequest.onsuccess = function (event) {
  69427. };
  69428. addRequest.onerror = function (event) {
  69429. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69430. };
  69431. }
  69432. catch (ex) {
  69433. callback(fileData);
  69434. }
  69435. }
  69436. else {
  69437. callback(fileData);
  69438. }
  69439. }
  69440. else {
  69441. callback();
  69442. }
  69443. }, false);
  69444. xhr.addEventListener("error", function (event) {
  69445. BABYLON.Tools.Error("error on XHR request.");
  69446. callback();
  69447. }, false);
  69448. xhr.send();
  69449. }
  69450. else {
  69451. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69452. callback();
  69453. }
  69454. };
  69455. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69456. Database.IsUASupportingBlobStorage = true;
  69457. /** Gets a boolean indicating if Database storate is enabled */
  69458. Database.IDBStorageEnabled = true;
  69459. Database._ParseURL = function (url) {
  69460. var a = document.createElement('a');
  69461. a.href = url;
  69462. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69463. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69464. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69465. return absLocation;
  69466. };
  69467. Database._ReturnFullUrlLocation = function (url) {
  69468. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69469. return (Database._ParseURL(window.location.href) + url);
  69470. }
  69471. else {
  69472. return url;
  69473. }
  69474. };
  69475. return Database;
  69476. }());
  69477. BABYLON.Database = Database;
  69478. })(BABYLON || (BABYLON = {}));
  69479. //# sourceMappingURL=babylon.database.js.map
  69480. var BABYLON;
  69481. (function (BABYLON) {
  69482. var FresnelParameters = /** @class */ (function () {
  69483. function FresnelParameters() {
  69484. this._isEnabled = true;
  69485. this.leftColor = BABYLON.Color3.White();
  69486. this.rightColor = BABYLON.Color3.Black();
  69487. this.bias = 0;
  69488. this.power = 1;
  69489. }
  69490. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69491. get: function () {
  69492. return this._isEnabled;
  69493. },
  69494. set: function (value) {
  69495. if (this._isEnabled === value) {
  69496. return;
  69497. }
  69498. this._isEnabled = value;
  69499. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69500. },
  69501. enumerable: true,
  69502. configurable: true
  69503. });
  69504. FresnelParameters.prototype.clone = function () {
  69505. var newFresnelParameters = new FresnelParameters();
  69506. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69507. return newFresnelParameters;
  69508. };
  69509. FresnelParameters.prototype.serialize = function () {
  69510. var serializationObject = {};
  69511. serializationObject.isEnabled = this.isEnabled;
  69512. serializationObject.leftColor = this.leftColor.asArray();
  69513. serializationObject.rightColor = this.rightColor.asArray();
  69514. serializationObject.bias = this.bias;
  69515. serializationObject.power = this.power;
  69516. return serializationObject;
  69517. };
  69518. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69519. var fresnelParameters = new FresnelParameters();
  69520. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69521. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69522. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69523. fresnelParameters.bias = parsedFresnelParameters.bias;
  69524. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69525. return fresnelParameters;
  69526. };
  69527. return FresnelParameters;
  69528. }());
  69529. BABYLON.FresnelParameters = FresnelParameters;
  69530. })(BABYLON || (BABYLON = {}));
  69531. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69532. var BABYLON;
  69533. (function (BABYLON) {
  69534. var MultiMaterial = /** @class */ (function (_super) {
  69535. __extends(MultiMaterial, _super);
  69536. function MultiMaterial(name, scene) {
  69537. var _this = _super.call(this, name, scene, true) || this;
  69538. scene.multiMaterials.push(_this);
  69539. _this.subMaterials = new Array();
  69540. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69541. return _this;
  69542. }
  69543. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69544. get: function () {
  69545. return this._subMaterials;
  69546. },
  69547. set: function (value) {
  69548. this._subMaterials = value;
  69549. this._hookArray(value);
  69550. },
  69551. enumerable: true,
  69552. configurable: true
  69553. });
  69554. MultiMaterial.prototype._hookArray = function (array) {
  69555. var _this = this;
  69556. var oldPush = array.push;
  69557. array.push = function () {
  69558. var items = [];
  69559. for (var _i = 0; _i < arguments.length; _i++) {
  69560. items[_i] = arguments[_i];
  69561. }
  69562. var result = oldPush.apply(array, items);
  69563. _this._markAllSubMeshesAsTexturesDirty();
  69564. return result;
  69565. };
  69566. var oldSplice = array.splice;
  69567. array.splice = function (index, deleteCount) {
  69568. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69569. _this._markAllSubMeshesAsTexturesDirty();
  69570. return deleted;
  69571. };
  69572. };
  69573. // Properties
  69574. MultiMaterial.prototype.getSubMaterial = function (index) {
  69575. if (index < 0 || index >= this.subMaterials.length) {
  69576. return this.getScene().defaultMaterial;
  69577. }
  69578. return this.subMaterials[index];
  69579. };
  69580. MultiMaterial.prototype.getActiveTextures = function () {
  69581. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69582. if (subMaterial) {
  69583. return subMaterial.getActiveTextures();
  69584. }
  69585. else {
  69586. return [];
  69587. }
  69588. }));
  69589. var _a;
  69590. };
  69591. // Methods
  69592. MultiMaterial.prototype.getClassName = function () {
  69593. return "MultiMaterial";
  69594. };
  69595. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69596. for (var index = 0; index < this.subMaterials.length; index++) {
  69597. var subMaterial = this.subMaterials[index];
  69598. if (subMaterial) {
  69599. if (subMaterial.storeEffectOnSubMeshes) {
  69600. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69601. return false;
  69602. }
  69603. continue;
  69604. }
  69605. if (!subMaterial.isReady(mesh)) {
  69606. return false;
  69607. }
  69608. }
  69609. }
  69610. return true;
  69611. };
  69612. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69613. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69614. for (var index = 0; index < this.subMaterials.length; index++) {
  69615. var subMaterial = null;
  69616. var current = this.subMaterials[index];
  69617. if (cloneChildren && current) {
  69618. subMaterial = current.clone(name + "-" + current.name);
  69619. }
  69620. else {
  69621. subMaterial = this.subMaterials[index];
  69622. }
  69623. newMultiMaterial.subMaterials.push(subMaterial);
  69624. }
  69625. return newMultiMaterial;
  69626. };
  69627. MultiMaterial.prototype.serialize = function () {
  69628. var serializationObject = {};
  69629. serializationObject.name = this.name;
  69630. serializationObject.id = this.id;
  69631. if (BABYLON.Tags) {
  69632. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69633. }
  69634. serializationObject.materials = [];
  69635. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69636. var subMat = this.subMaterials[matIndex];
  69637. if (subMat) {
  69638. serializationObject.materials.push(subMat.id);
  69639. }
  69640. else {
  69641. serializationObject.materials.push(null);
  69642. }
  69643. }
  69644. return serializationObject;
  69645. };
  69646. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69647. var scene = this.getScene();
  69648. if (!scene) {
  69649. return;
  69650. }
  69651. var index = scene.multiMaterials.indexOf(this);
  69652. if (index >= 0) {
  69653. scene.multiMaterials.splice(index, 1);
  69654. }
  69655. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69656. };
  69657. return MultiMaterial;
  69658. }(BABYLON.Material));
  69659. BABYLON.MultiMaterial = MultiMaterial;
  69660. })(BABYLON || (BABYLON = {}));
  69661. //# sourceMappingURL=babylon.multiMaterial.js.map
  69662. var BABYLON;
  69663. (function (BABYLON) {
  69664. var FreeCameraTouchInput = /** @class */ (function () {
  69665. function FreeCameraTouchInput() {
  69666. this._offsetX = null;
  69667. this._offsetY = null;
  69668. this._pointerPressed = new Array();
  69669. this.touchAngularSensibility = 200000.0;
  69670. this.touchMoveSensibility = 250.0;
  69671. }
  69672. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69673. var _this = this;
  69674. var previousPosition = null;
  69675. if (this._pointerInput === undefined) {
  69676. this._onLostFocus = function (evt) {
  69677. _this._offsetX = null;
  69678. _this._offsetY = null;
  69679. };
  69680. this._pointerInput = function (p, s) {
  69681. var evt = p.event;
  69682. if (evt.pointerType === "mouse") {
  69683. return;
  69684. }
  69685. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69686. if (!noPreventDefault) {
  69687. evt.preventDefault();
  69688. }
  69689. _this._pointerPressed.push(evt.pointerId);
  69690. if (_this._pointerPressed.length !== 1) {
  69691. return;
  69692. }
  69693. previousPosition = {
  69694. x: evt.clientX,
  69695. y: evt.clientY
  69696. };
  69697. }
  69698. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69699. if (!noPreventDefault) {
  69700. evt.preventDefault();
  69701. }
  69702. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69703. if (index === -1) {
  69704. return;
  69705. }
  69706. _this._pointerPressed.splice(index, 1);
  69707. if (index != 0) {
  69708. return;
  69709. }
  69710. previousPosition = null;
  69711. _this._offsetX = null;
  69712. _this._offsetY = null;
  69713. }
  69714. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69715. if (!noPreventDefault) {
  69716. evt.preventDefault();
  69717. }
  69718. if (!previousPosition) {
  69719. return;
  69720. }
  69721. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69722. if (index != 0) {
  69723. return;
  69724. }
  69725. _this._offsetX = evt.clientX - previousPosition.x;
  69726. _this._offsetY = -(evt.clientY - previousPosition.y);
  69727. }
  69728. };
  69729. }
  69730. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69731. if (this._onLostFocus) {
  69732. element.addEventListener("blur", this._onLostFocus);
  69733. }
  69734. };
  69735. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69736. if (this._pointerInput && element) {
  69737. if (this._observer) {
  69738. this.camera.getScene().onPointerObservable.remove(this._observer);
  69739. this._observer = null;
  69740. }
  69741. if (this._onLostFocus) {
  69742. element.removeEventListener("blur", this._onLostFocus);
  69743. this._onLostFocus = null;
  69744. }
  69745. this._pointerPressed = [];
  69746. this._offsetX = null;
  69747. this._offsetY = null;
  69748. }
  69749. };
  69750. FreeCameraTouchInput.prototype.checkInputs = function () {
  69751. if (this._offsetX && this._offsetY) {
  69752. var camera = this.camera;
  69753. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69754. if (this._pointerPressed.length > 1) {
  69755. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69756. }
  69757. else {
  69758. var speed = camera._computeLocalCameraSpeed();
  69759. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69760. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69761. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69762. }
  69763. }
  69764. };
  69765. FreeCameraTouchInput.prototype.getClassName = function () {
  69766. return "FreeCameraTouchInput";
  69767. };
  69768. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69769. return "touch";
  69770. };
  69771. __decorate([
  69772. BABYLON.serialize()
  69773. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69774. __decorate([
  69775. BABYLON.serialize()
  69776. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69777. return FreeCameraTouchInput;
  69778. }());
  69779. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69780. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69781. })(BABYLON || (BABYLON = {}));
  69782. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69783. var BABYLON;
  69784. (function (BABYLON) {
  69785. // We're mainly based on the logic defined into the FreeCamera code
  69786. var TouchCamera = /** @class */ (function (_super) {
  69787. __extends(TouchCamera, _super);
  69788. //-- end properties for backward compatibility for inputs
  69789. function TouchCamera(name, position, scene) {
  69790. var _this = _super.call(this, name, position, scene) || this;
  69791. _this.inputs.addTouch();
  69792. _this._setupInputs();
  69793. return _this;
  69794. }
  69795. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69796. //-- Begin properties for backward compatibility for inputs
  69797. get: function () {
  69798. var touch = this.inputs.attached["touch"];
  69799. if (touch)
  69800. return touch.touchAngularSensibility;
  69801. return 0;
  69802. },
  69803. set: function (value) {
  69804. var touch = this.inputs.attached["touch"];
  69805. if (touch)
  69806. touch.touchAngularSensibility = value;
  69807. },
  69808. enumerable: true,
  69809. configurable: true
  69810. });
  69811. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69812. get: function () {
  69813. var touch = this.inputs.attached["touch"];
  69814. if (touch)
  69815. return touch.touchMoveSensibility;
  69816. return 0;
  69817. },
  69818. set: function (value) {
  69819. var touch = this.inputs.attached["touch"];
  69820. if (touch)
  69821. touch.touchMoveSensibility = value;
  69822. },
  69823. enumerable: true,
  69824. configurable: true
  69825. });
  69826. TouchCamera.prototype.getClassName = function () {
  69827. return "TouchCamera";
  69828. };
  69829. TouchCamera.prototype._setupInputs = function () {
  69830. var mouse = this.inputs.attached["mouse"];
  69831. if (mouse) {
  69832. mouse.touchEnabled = false;
  69833. }
  69834. };
  69835. return TouchCamera;
  69836. }(BABYLON.FreeCamera));
  69837. BABYLON.TouchCamera = TouchCamera;
  69838. })(BABYLON || (BABYLON = {}));
  69839. //# sourceMappingURL=babylon.touchCamera.js.map
  69840. var BABYLON;
  69841. (function (BABYLON) {
  69842. var ProceduralTexture = /** @class */ (function (_super) {
  69843. __extends(ProceduralTexture, _super);
  69844. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69845. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69846. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69847. if (isCube === void 0) { isCube = false; }
  69848. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69849. _this.isCube = isCube;
  69850. _this.isEnabled = true;
  69851. _this._currentRefreshId = -1;
  69852. _this._refreshRate = 1;
  69853. _this._vertexBuffers = {};
  69854. _this._uniforms = new Array();
  69855. _this._samplers = new Array();
  69856. _this._textures = {};
  69857. _this._floats = {};
  69858. _this._floatsArrays = {};
  69859. _this._colors3 = {};
  69860. _this._colors4 = {};
  69861. _this._vectors2 = {};
  69862. _this._vectors3 = {};
  69863. _this._matrices = {};
  69864. _this._fallbackTextureUsed = false;
  69865. scene.proceduralTextures.push(_this);
  69866. _this._engine = scene.getEngine();
  69867. _this.name = name;
  69868. _this.isRenderTarget = true;
  69869. _this._size = size;
  69870. _this._generateMipMaps = generateMipMaps;
  69871. _this.setFragment(fragment);
  69872. _this._fallbackTexture = fallbackTexture;
  69873. if (isCube) {
  69874. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69875. _this.setFloat("face", 0);
  69876. }
  69877. else {
  69878. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69879. }
  69880. // VBO
  69881. var vertices = [];
  69882. vertices.push(1, 1);
  69883. vertices.push(-1, 1);
  69884. vertices.push(-1, -1);
  69885. vertices.push(1, -1);
  69886. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69887. _this._createIndexBuffer();
  69888. return _this;
  69889. }
  69890. ProceduralTexture.prototype._createIndexBuffer = function () {
  69891. var engine = this._engine;
  69892. // Indices
  69893. var indices = [];
  69894. indices.push(0);
  69895. indices.push(1);
  69896. indices.push(2);
  69897. indices.push(0);
  69898. indices.push(2);
  69899. indices.push(3);
  69900. this._indexBuffer = engine.createIndexBuffer(indices);
  69901. };
  69902. ProceduralTexture.prototype._rebuild = function () {
  69903. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69904. if (vb) {
  69905. vb._rebuild();
  69906. }
  69907. this._createIndexBuffer();
  69908. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69909. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69910. }
  69911. };
  69912. ProceduralTexture.prototype.reset = function () {
  69913. if (this._effect === undefined) {
  69914. return;
  69915. }
  69916. var engine = this._engine;
  69917. engine._releaseEffect(this._effect);
  69918. };
  69919. ProceduralTexture.prototype.isReady = function () {
  69920. var _this = this;
  69921. var engine = this._engine;
  69922. var shaders;
  69923. if (!this._fragment) {
  69924. return false;
  69925. }
  69926. if (this._fallbackTextureUsed) {
  69927. return true;
  69928. }
  69929. if (this._fragment.fragmentElement !== undefined) {
  69930. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69931. }
  69932. else {
  69933. shaders = { vertex: "procedural", fragment: this._fragment };
  69934. }
  69935. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69936. _this.releaseInternalTexture();
  69937. if (_this._fallbackTexture) {
  69938. _this._texture = _this._fallbackTexture._texture;
  69939. if (_this._texture) {
  69940. _this._texture.incrementReferences();
  69941. }
  69942. }
  69943. _this._fallbackTextureUsed = true;
  69944. });
  69945. return this._effect.isReady();
  69946. };
  69947. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69948. this._currentRefreshId = -1;
  69949. };
  69950. ProceduralTexture.prototype.setFragment = function (fragment) {
  69951. this._fragment = fragment;
  69952. };
  69953. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69954. get: function () {
  69955. return this._refreshRate;
  69956. },
  69957. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69958. set: function (value) {
  69959. this._refreshRate = value;
  69960. this.resetRefreshCounter();
  69961. },
  69962. enumerable: true,
  69963. configurable: true
  69964. });
  69965. ProceduralTexture.prototype._shouldRender = function () {
  69966. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69967. return false;
  69968. }
  69969. if (this._fallbackTextureUsed) {
  69970. return false;
  69971. }
  69972. if (this._currentRefreshId === -1) { // At least render once
  69973. this._currentRefreshId = 1;
  69974. return true;
  69975. }
  69976. if (this.refreshRate === this._currentRefreshId) {
  69977. this._currentRefreshId = 1;
  69978. return true;
  69979. }
  69980. this._currentRefreshId++;
  69981. return false;
  69982. };
  69983. ProceduralTexture.prototype.getRenderSize = function () {
  69984. return this._size;
  69985. };
  69986. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69987. if (this._fallbackTextureUsed) {
  69988. return;
  69989. }
  69990. this.releaseInternalTexture();
  69991. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69992. // Update properties
  69993. this._size = size;
  69994. this._generateMipMaps = generateMipMaps;
  69995. };
  69996. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69997. if (this._uniforms.indexOf(uniformName) === -1) {
  69998. this._uniforms.push(uniformName);
  69999. }
  70000. };
  70001. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70002. if (this._samplers.indexOf(name) === -1) {
  70003. this._samplers.push(name);
  70004. }
  70005. this._textures[name] = texture;
  70006. return this;
  70007. };
  70008. ProceduralTexture.prototype.setFloat = function (name, value) {
  70009. this._checkUniform(name);
  70010. this._floats[name] = value;
  70011. return this;
  70012. };
  70013. ProceduralTexture.prototype.setFloats = function (name, value) {
  70014. this._checkUniform(name);
  70015. this._floatsArrays[name] = value;
  70016. return this;
  70017. };
  70018. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70019. this._checkUniform(name);
  70020. this._colors3[name] = value;
  70021. return this;
  70022. };
  70023. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70024. this._checkUniform(name);
  70025. this._colors4[name] = value;
  70026. return this;
  70027. };
  70028. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70029. this._checkUniform(name);
  70030. this._vectors2[name] = value;
  70031. return this;
  70032. };
  70033. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70034. this._checkUniform(name);
  70035. this._vectors3[name] = value;
  70036. return this;
  70037. };
  70038. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70039. this._checkUniform(name);
  70040. this._matrices[name] = value;
  70041. return this;
  70042. };
  70043. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70044. var scene = this.getScene();
  70045. if (!scene) {
  70046. return;
  70047. }
  70048. var engine = this._engine;
  70049. // Render
  70050. engine.enableEffect(this._effect);
  70051. engine.setState(false);
  70052. // Texture
  70053. for (var name in this._textures) {
  70054. this._effect.setTexture(name, this._textures[name]);
  70055. }
  70056. // Float
  70057. for (name in this._floats) {
  70058. this._effect.setFloat(name, this._floats[name]);
  70059. }
  70060. // Floats
  70061. for (name in this._floatsArrays) {
  70062. this._effect.setArray(name, this._floatsArrays[name]);
  70063. }
  70064. // Color3
  70065. for (name in this._colors3) {
  70066. this._effect.setColor3(name, this._colors3[name]);
  70067. }
  70068. // Color4
  70069. for (name in this._colors4) {
  70070. var color = this._colors4[name];
  70071. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70072. }
  70073. // Vector2
  70074. for (name in this._vectors2) {
  70075. this._effect.setVector2(name, this._vectors2[name]);
  70076. }
  70077. // Vector3
  70078. for (name in this._vectors3) {
  70079. this._effect.setVector3(name, this._vectors3[name]);
  70080. }
  70081. // Matrix
  70082. for (name in this._matrices) {
  70083. this._effect.setMatrix(name, this._matrices[name]);
  70084. }
  70085. if (!this._texture) {
  70086. return;
  70087. }
  70088. if (this.isCube) {
  70089. for (var face = 0; face < 6; face++) {
  70090. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70091. // VBOs
  70092. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70093. this._effect.setFloat("face", face);
  70094. // Clear
  70095. engine.clear(scene.clearColor, true, true, true);
  70096. // Draw order
  70097. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70098. // Mipmaps
  70099. if (face === 5) {
  70100. engine.generateMipMapsForCubemap(this._texture);
  70101. }
  70102. }
  70103. }
  70104. else {
  70105. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70106. // VBOs
  70107. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70108. // Clear
  70109. engine.clear(scene.clearColor, true, true, true);
  70110. // Draw order
  70111. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70112. }
  70113. // Unbind
  70114. engine.unBindFramebuffer(this._texture, this.isCube);
  70115. if (this.onGenerated) {
  70116. this.onGenerated();
  70117. }
  70118. };
  70119. ProceduralTexture.prototype.clone = function () {
  70120. var textureSize = this.getSize();
  70121. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70122. // Base texture
  70123. newTexture.hasAlpha = this.hasAlpha;
  70124. newTexture.level = this.level;
  70125. // RenderTarget Texture
  70126. newTexture.coordinatesMode = this.coordinatesMode;
  70127. return newTexture;
  70128. };
  70129. ProceduralTexture.prototype.dispose = function () {
  70130. var scene = this.getScene();
  70131. if (!scene) {
  70132. return;
  70133. }
  70134. var index = scene.proceduralTextures.indexOf(this);
  70135. if (index >= 0) {
  70136. scene.proceduralTextures.splice(index, 1);
  70137. }
  70138. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70139. if (vertexBuffer) {
  70140. vertexBuffer.dispose();
  70141. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70142. }
  70143. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70144. this._indexBuffer = null;
  70145. }
  70146. _super.prototype.dispose.call(this);
  70147. };
  70148. __decorate([
  70149. BABYLON.serialize()
  70150. ], ProceduralTexture.prototype, "_size", void 0);
  70151. __decorate([
  70152. BABYLON.serialize()
  70153. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70154. __decorate([
  70155. BABYLON.serialize()
  70156. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70157. __decorate([
  70158. BABYLON.serialize()
  70159. ], ProceduralTexture.prototype, "refreshRate", null);
  70160. return ProceduralTexture;
  70161. }(BABYLON.Texture));
  70162. BABYLON.ProceduralTexture = ProceduralTexture;
  70163. })(BABYLON || (BABYLON = {}));
  70164. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70165. var BABYLON;
  70166. (function (BABYLON) {
  70167. var CustomProceduralTexture = /** @class */ (function (_super) {
  70168. __extends(CustomProceduralTexture, _super);
  70169. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70170. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70171. _this._animate = true;
  70172. _this._time = 0;
  70173. _this._texturePath = texturePath;
  70174. //Try to load json
  70175. _this.loadJson(texturePath);
  70176. _this.refreshRate = 1;
  70177. return _this;
  70178. }
  70179. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70180. var _this = this;
  70181. var noConfigFile = function () {
  70182. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70183. try {
  70184. _this.setFragment(_this._texturePath);
  70185. }
  70186. catch (ex) {
  70187. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70188. }
  70189. };
  70190. var configFileUrl = jsonUrl + "/config.json";
  70191. var xhr = new XMLHttpRequest();
  70192. xhr.open("GET", configFileUrl, true);
  70193. xhr.addEventListener("load", function () {
  70194. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70195. try {
  70196. _this._config = JSON.parse(xhr.response);
  70197. _this.updateShaderUniforms();
  70198. _this.updateTextures();
  70199. _this.setFragment(_this._texturePath + "/custom");
  70200. _this._animate = _this._config.animate;
  70201. _this.refreshRate = _this._config.refreshrate;
  70202. }
  70203. catch (ex) {
  70204. noConfigFile();
  70205. }
  70206. }
  70207. else {
  70208. noConfigFile();
  70209. }
  70210. }, false);
  70211. xhr.addEventListener("error", function () {
  70212. noConfigFile();
  70213. }, false);
  70214. try {
  70215. xhr.send();
  70216. }
  70217. catch (ex) {
  70218. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70219. }
  70220. };
  70221. CustomProceduralTexture.prototype.isReady = function () {
  70222. if (!_super.prototype.isReady.call(this)) {
  70223. return false;
  70224. }
  70225. for (var name in this._textures) {
  70226. var texture = this._textures[name];
  70227. if (!texture.isReady()) {
  70228. return false;
  70229. }
  70230. }
  70231. return true;
  70232. };
  70233. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70234. var scene = this.getScene();
  70235. if (this._animate && scene) {
  70236. this._time += scene.getAnimationRatio() * 0.03;
  70237. this.updateShaderUniforms();
  70238. }
  70239. _super.prototype.render.call(this, useCameraPostProcess);
  70240. };
  70241. CustomProceduralTexture.prototype.updateTextures = function () {
  70242. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70243. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70244. }
  70245. };
  70246. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70247. if (this._config) {
  70248. for (var j = 0; j < this._config.uniforms.length; j++) {
  70249. var uniform = this._config.uniforms[j];
  70250. switch (uniform.type) {
  70251. case "float":
  70252. this.setFloat(uniform.name, uniform.value);
  70253. break;
  70254. case "color3":
  70255. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70256. break;
  70257. case "color4":
  70258. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70259. break;
  70260. case "vector2":
  70261. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70262. break;
  70263. case "vector3":
  70264. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70265. break;
  70266. }
  70267. }
  70268. }
  70269. this.setFloat("time", this._time);
  70270. };
  70271. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70272. get: function () {
  70273. return this._animate;
  70274. },
  70275. set: function (value) {
  70276. this._animate = value;
  70277. },
  70278. enumerable: true,
  70279. configurable: true
  70280. });
  70281. return CustomProceduralTexture;
  70282. }(BABYLON.ProceduralTexture));
  70283. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70284. })(BABYLON || (BABYLON = {}));
  70285. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70286. var BABYLON;
  70287. (function (BABYLON) {
  70288. var FreeCameraGamepadInput = /** @class */ (function () {
  70289. function FreeCameraGamepadInput() {
  70290. this.gamepadAngularSensibility = 200;
  70291. this.gamepadMoveSensibility = 40;
  70292. // private members
  70293. this._cameraTransform = BABYLON.Matrix.Identity();
  70294. this._deltaTransform = BABYLON.Vector3.Zero();
  70295. this._vector3 = BABYLON.Vector3.Zero();
  70296. this._vector2 = BABYLON.Vector2.Zero();
  70297. }
  70298. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70299. var _this = this;
  70300. var manager = this.camera.getScene().gamepadManager;
  70301. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70302. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70303. // prioritize XBOX gamepads.
  70304. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70305. _this.gamepad = gamepad;
  70306. }
  70307. }
  70308. });
  70309. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70310. if (_this.gamepad === gamepad) {
  70311. _this.gamepad = null;
  70312. }
  70313. });
  70314. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70315. };
  70316. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70317. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70318. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70319. this.gamepad = null;
  70320. };
  70321. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70322. if (this.gamepad && this.gamepad.leftStick) {
  70323. var camera = this.camera;
  70324. var LSValues = this.gamepad.leftStick;
  70325. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70326. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70327. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70328. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70329. var RSValues = this.gamepad.rightStick;
  70330. if (RSValues) {
  70331. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70332. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70333. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70334. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70335. }
  70336. else {
  70337. RSValues = { x: 0, y: 0 };
  70338. }
  70339. if (!camera.rotationQuaternion) {
  70340. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70341. }
  70342. else {
  70343. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70344. }
  70345. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70346. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70347. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70348. camera.cameraDirection.addInPlace(this._deltaTransform);
  70349. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70350. camera.cameraRotation.addInPlace(this._vector2);
  70351. }
  70352. };
  70353. FreeCameraGamepadInput.prototype.getClassName = function () {
  70354. return "FreeCameraGamepadInput";
  70355. };
  70356. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70357. return "gamepad";
  70358. };
  70359. __decorate([
  70360. BABYLON.serialize()
  70361. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70362. __decorate([
  70363. BABYLON.serialize()
  70364. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70365. return FreeCameraGamepadInput;
  70366. }());
  70367. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70368. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70369. })(BABYLON || (BABYLON = {}));
  70370. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70371. var BABYLON;
  70372. (function (BABYLON) {
  70373. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70374. function ArcRotateCameraGamepadInput() {
  70375. this.gamepadRotationSensibility = 80;
  70376. this.gamepadMoveSensibility = 40;
  70377. }
  70378. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70379. var _this = this;
  70380. var manager = this.camera.getScene().gamepadManager;
  70381. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70382. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70383. // prioritize XBOX gamepads.
  70384. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70385. _this.gamepad = gamepad;
  70386. }
  70387. }
  70388. });
  70389. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70390. if (_this.gamepad === gamepad) {
  70391. _this.gamepad = null;
  70392. }
  70393. });
  70394. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70395. };
  70396. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70397. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70398. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70399. this.gamepad = null;
  70400. };
  70401. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70402. if (this.gamepad) {
  70403. var camera = this.camera;
  70404. var RSValues = this.gamepad.rightStick;
  70405. if (RSValues) {
  70406. if (RSValues.x != 0) {
  70407. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70408. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70409. camera.inertialAlphaOffset += normalizedRX;
  70410. }
  70411. }
  70412. if (RSValues.y != 0) {
  70413. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70414. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70415. camera.inertialBetaOffset += normalizedRY;
  70416. }
  70417. }
  70418. }
  70419. var LSValues = this.gamepad.leftStick;
  70420. if (LSValues && LSValues.y != 0) {
  70421. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70422. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70423. this.camera.inertialRadiusOffset -= normalizedLY;
  70424. }
  70425. }
  70426. }
  70427. };
  70428. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70429. return "ArcRotateCameraGamepadInput";
  70430. };
  70431. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70432. return "gamepad";
  70433. };
  70434. __decorate([
  70435. BABYLON.serialize()
  70436. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70437. __decorate([
  70438. BABYLON.serialize()
  70439. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70440. return ArcRotateCameraGamepadInput;
  70441. }());
  70442. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70443. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70444. })(BABYLON || (BABYLON = {}));
  70445. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70446. var BABYLON;
  70447. (function (BABYLON) {
  70448. var GamepadManager = /** @class */ (function () {
  70449. function GamepadManager(_scene) {
  70450. var _this = this;
  70451. this._scene = _scene;
  70452. this._babylonGamepads = [];
  70453. this._oneGamepadConnected = false;
  70454. this._isMonitoring = false;
  70455. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70456. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70457. this._gamepadEventSupported = false;
  70458. }
  70459. else {
  70460. this._gamepadEventSupported = 'GamepadEvent' in window;
  70461. this._gamepadSupport = (navigator.getGamepads ||
  70462. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70463. }
  70464. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70465. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70466. for (var i in _this._babylonGamepads) {
  70467. var gamepad = _this._babylonGamepads[i];
  70468. if (gamepad && gamepad._isConnected) {
  70469. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70470. }
  70471. }
  70472. });
  70473. this._onGamepadConnectedEvent = function (evt) {
  70474. var gamepad = evt.gamepad;
  70475. if (gamepad.index in _this._babylonGamepads) {
  70476. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70477. return;
  70478. }
  70479. }
  70480. var newGamepad;
  70481. if (_this._babylonGamepads[gamepad.index]) {
  70482. newGamepad = _this._babylonGamepads[gamepad.index];
  70483. newGamepad.browserGamepad = gamepad;
  70484. newGamepad._isConnected = true;
  70485. }
  70486. else {
  70487. newGamepad = _this._addNewGamepad(gamepad);
  70488. }
  70489. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70490. _this._startMonitoringGamepads();
  70491. };
  70492. this._onGamepadDisconnectedEvent = function (evt) {
  70493. var gamepad = evt.gamepad;
  70494. // Remove the gamepad from the list of gamepads to monitor.
  70495. for (var i in _this._babylonGamepads) {
  70496. if (_this._babylonGamepads[i].index === gamepad.index) {
  70497. var disconnectedGamepad = _this._babylonGamepads[i];
  70498. disconnectedGamepad._isConnected = false;
  70499. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70500. break;
  70501. }
  70502. }
  70503. };
  70504. if (this._gamepadSupport) {
  70505. //first add already-connected gamepads
  70506. this._updateGamepadObjects();
  70507. if (this._babylonGamepads.length) {
  70508. this._startMonitoringGamepads();
  70509. }
  70510. // Checking if the gamepad connected event is supported (like in Firefox)
  70511. if (this._gamepadEventSupported) {
  70512. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70513. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70514. }
  70515. else {
  70516. this._startMonitoringGamepads();
  70517. }
  70518. }
  70519. }
  70520. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70521. get: function () {
  70522. return this._babylonGamepads;
  70523. },
  70524. enumerable: true,
  70525. configurable: true
  70526. });
  70527. GamepadManager.prototype.getGamepadByType = function (type) {
  70528. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70529. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70530. var gamepad = _a[_i];
  70531. if (gamepad && gamepad.type === type) {
  70532. return gamepad;
  70533. }
  70534. }
  70535. return null;
  70536. };
  70537. GamepadManager.prototype.dispose = function () {
  70538. if (this._gamepadEventSupported) {
  70539. if (this._onGamepadConnectedEvent) {
  70540. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70541. }
  70542. if (this._onGamepadDisconnectedEvent) {
  70543. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70544. }
  70545. this._onGamepadConnectedEvent = null;
  70546. this._onGamepadDisconnectedEvent = null;
  70547. }
  70548. this._babylonGamepads.forEach(function (gamepad) {
  70549. gamepad.dispose();
  70550. });
  70551. this.onGamepadConnectedObservable.clear();
  70552. this.onGamepadDisconnectedObservable.clear();
  70553. this._oneGamepadConnected = false;
  70554. this._stopMonitoringGamepads();
  70555. this._babylonGamepads = [];
  70556. };
  70557. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70558. if (!this._oneGamepadConnected) {
  70559. this._oneGamepadConnected = true;
  70560. }
  70561. var newGamepad;
  70562. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70563. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70564. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70565. }
  70566. // if pose is supported, use the (WebVR) pose enabled controller
  70567. else if (gamepad.pose) {
  70568. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70569. }
  70570. else {
  70571. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70572. }
  70573. this._babylonGamepads[newGamepad.index] = newGamepad;
  70574. return newGamepad;
  70575. };
  70576. GamepadManager.prototype._startMonitoringGamepads = function () {
  70577. if (!this._isMonitoring) {
  70578. this._isMonitoring = true;
  70579. //back-comp
  70580. if (!this._scene) {
  70581. this._checkGamepadsStatus();
  70582. }
  70583. }
  70584. };
  70585. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70586. this._isMonitoring = false;
  70587. };
  70588. GamepadManager.prototype._checkGamepadsStatus = function () {
  70589. var _this = this;
  70590. // Hack to be compatible Chrome
  70591. this._updateGamepadObjects();
  70592. for (var i in this._babylonGamepads) {
  70593. var gamepad = this._babylonGamepads[i];
  70594. if (!gamepad || !gamepad.isConnected) {
  70595. continue;
  70596. }
  70597. gamepad.update();
  70598. }
  70599. if (this._isMonitoring && !this._scene) {
  70600. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70601. }
  70602. };
  70603. // This function is called only on Chrome, which does not properly support
  70604. // connection/disconnection events and forces you to recopy again the gamepad object
  70605. GamepadManager.prototype._updateGamepadObjects = function () {
  70606. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70607. for (var i = 0; i < gamepads.length; i++) {
  70608. var gamepad = gamepads[i];
  70609. if (gamepad) {
  70610. if (!this._babylonGamepads[gamepad.index]) {
  70611. var newGamepad = this._addNewGamepad(gamepad);
  70612. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70613. }
  70614. else {
  70615. // Forced to copy again this object for Chrome for unknown reason
  70616. this._babylonGamepads[i].browserGamepad = gamepad;
  70617. if (!this._babylonGamepads[i].isConnected) {
  70618. this._babylonGamepads[i]._isConnected = true;
  70619. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70620. }
  70621. }
  70622. }
  70623. }
  70624. };
  70625. return GamepadManager;
  70626. }());
  70627. BABYLON.GamepadManager = GamepadManager;
  70628. })(BABYLON || (BABYLON = {}));
  70629. //# sourceMappingURL=babylon.gamepadManager.js.map
  70630. var BABYLON;
  70631. (function (BABYLON) {
  70632. var StickValues = /** @class */ (function () {
  70633. function StickValues(x, y) {
  70634. this.x = x;
  70635. this.y = y;
  70636. }
  70637. return StickValues;
  70638. }());
  70639. BABYLON.StickValues = StickValues;
  70640. var Gamepad = /** @class */ (function () {
  70641. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70642. if (leftStickX === void 0) { leftStickX = 0; }
  70643. if (leftStickY === void 0) { leftStickY = 1; }
  70644. if (rightStickX === void 0) { rightStickX = 2; }
  70645. if (rightStickY === void 0) { rightStickY = 3; }
  70646. this.id = id;
  70647. this.index = index;
  70648. this.browserGamepad = browserGamepad;
  70649. this._isConnected = true;
  70650. this._invertLeftStickY = false;
  70651. this.type = Gamepad.GAMEPAD;
  70652. this._leftStickAxisX = leftStickX;
  70653. this._leftStickAxisY = leftStickY;
  70654. this._rightStickAxisX = rightStickX;
  70655. this._rightStickAxisY = rightStickY;
  70656. if (this.browserGamepad.axes.length >= 2) {
  70657. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70658. }
  70659. if (this.browserGamepad.axes.length >= 4) {
  70660. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70661. }
  70662. }
  70663. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70664. get: function () {
  70665. return this._isConnected;
  70666. },
  70667. enumerable: true,
  70668. configurable: true
  70669. });
  70670. Gamepad.prototype.onleftstickchanged = function (callback) {
  70671. this._onleftstickchanged = callback;
  70672. };
  70673. Gamepad.prototype.onrightstickchanged = function (callback) {
  70674. this._onrightstickchanged = callback;
  70675. };
  70676. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70677. get: function () {
  70678. return this._leftStick;
  70679. },
  70680. set: function (newValues) {
  70681. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70682. this._onleftstickchanged(newValues);
  70683. }
  70684. this._leftStick = newValues;
  70685. },
  70686. enumerable: true,
  70687. configurable: true
  70688. });
  70689. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70690. get: function () {
  70691. return this._rightStick;
  70692. },
  70693. set: function (newValues) {
  70694. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70695. this._onrightstickchanged(newValues);
  70696. }
  70697. this._rightStick = newValues;
  70698. },
  70699. enumerable: true,
  70700. configurable: true
  70701. });
  70702. Gamepad.prototype.update = function () {
  70703. if (this._leftStick) {
  70704. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70705. if (this._invertLeftStickY) {
  70706. this.leftStick.y *= -1;
  70707. }
  70708. }
  70709. if (this._rightStick) {
  70710. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70711. }
  70712. };
  70713. Gamepad.prototype.dispose = function () {
  70714. };
  70715. Gamepad.GAMEPAD = 0;
  70716. Gamepad.GENERIC = 1;
  70717. Gamepad.XBOX = 2;
  70718. Gamepad.POSE_ENABLED = 3;
  70719. return Gamepad;
  70720. }());
  70721. BABYLON.Gamepad = Gamepad;
  70722. var GenericPad = /** @class */ (function (_super) {
  70723. __extends(GenericPad, _super);
  70724. function GenericPad(id, index, browserGamepad) {
  70725. var _this = _super.call(this, id, index, browserGamepad) || this;
  70726. _this.onButtonDownObservable = new BABYLON.Observable();
  70727. _this.onButtonUpObservable = new BABYLON.Observable();
  70728. _this.type = Gamepad.GENERIC;
  70729. _this._buttons = new Array(browserGamepad.buttons.length);
  70730. return _this;
  70731. }
  70732. GenericPad.prototype.onbuttondown = function (callback) {
  70733. this._onbuttondown = callback;
  70734. };
  70735. GenericPad.prototype.onbuttonup = function (callback) {
  70736. this._onbuttonup = callback;
  70737. };
  70738. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70739. if (newValue !== currentValue) {
  70740. if (newValue === 1) {
  70741. if (this._onbuttondown) {
  70742. this._onbuttondown(buttonIndex);
  70743. }
  70744. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70745. }
  70746. if (newValue === 0) {
  70747. if (this._onbuttonup) {
  70748. this._onbuttonup(buttonIndex);
  70749. }
  70750. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70751. }
  70752. }
  70753. return newValue;
  70754. };
  70755. GenericPad.prototype.update = function () {
  70756. _super.prototype.update.call(this);
  70757. for (var index = 0; index < this._buttons.length; index++) {
  70758. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70759. }
  70760. };
  70761. GenericPad.prototype.dispose = function () {
  70762. _super.prototype.dispose.call(this);
  70763. this.onButtonDownObservable.clear();
  70764. this.onButtonUpObservable.clear();
  70765. };
  70766. return GenericPad;
  70767. }(Gamepad));
  70768. BABYLON.GenericPad = GenericPad;
  70769. })(BABYLON || (BABYLON = {}));
  70770. //# sourceMappingURL=babylon.gamepad.js.map
  70771. var BABYLON;
  70772. (function (BABYLON) {
  70773. /**
  70774. * Defines supported buttons for XBox360 compatible gamepads
  70775. */
  70776. var Xbox360Button;
  70777. (function (Xbox360Button) {
  70778. /** A */
  70779. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70780. /** B */
  70781. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70782. /** X */
  70783. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70784. /** Y */
  70785. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70786. /** Start */
  70787. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70788. /** Back */
  70789. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70790. /** Left button */
  70791. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70792. /** Right button */
  70793. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70794. /** Left stick */
  70795. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70796. /** Right stick */
  70797. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70798. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70799. /** Defines values for XBox360 DPad */
  70800. var Xbox360Dpad;
  70801. (function (Xbox360Dpad) {
  70802. /** Up */
  70803. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70804. /** Down */
  70805. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70806. /** Left */
  70807. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70808. /** Right */
  70809. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70810. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70811. /**
  70812. * Defines a XBox360 gamepad
  70813. */
  70814. var Xbox360Pad = /** @class */ (function (_super) {
  70815. __extends(Xbox360Pad, _super);
  70816. /**
  70817. * Creates a new XBox360 gamepad object
  70818. * @param id defines the id of this gamepad
  70819. * @param index defines its index
  70820. * @param gamepad defines the internal HTML gamepad object
  70821. * @param xboxOne defines if it is a XBox One gamepad
  70822. */
  70823. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70824. if (xboxOne === void 0) { xboxOne = false; }
  70825. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70826. _this._leftTrigger = 0;
  70827. _this._rightTrigger = 0;
  70828. /** Observable raised when a button is pressed */
  70829. _this.onButtonDownObservable = new BABYLON.Observable();
  70830. /** Observable raised when a button is released */
  70831. _this.onButtonUpObservable = new BABYLON.Observable();
  70832. /** Observable raised when a pad is pressed */
  70833. _this.onPadDownObservable = new BABYLON.Observable();
  70834. /** Observable raised when a pad is released */
  70835. _this.onPadUpObservable = new BABYLON.Observable();
  70836. _this._buttonA = 0;
  70837. _this._buttonB = 0;
  70838. _this._buttonX = 0;
  70839. _this._buttonY = 0;
  70840. _this._buttonBack = 0;
  70841. _this._buttonStart = 0;
  70842. _this._buttonLB = 0;
  70843. _this._buttonRB = 0;
  70844. _this._buttonLeftStick = 0;
  70845. _this._buttonRightStick = 0;
  70846. _this._dPadUp = 0;
  70847. _this._dPadDown = 0;
  70848. _this._dPadLeft = 0;
  70849. _this._dPadRight = 0;
  70850. _this._isXboxOnePad = false;
  70851. _this.type = BABYLON.Gamepad.XBOX;
  70852. _this._isXboxOnePad = xboxOne;
  70853. return _this;
  70854. }
  70855. /**
  70856. * Defines the callback to call when left trigger is pressed
  70857. * @param callback defines the callback to use
  70858. */
  70859. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70860. this._onlefttriggerchanged = callback;
  70861. };
  70862. /**
  70863. * Defines the callback to call when right trigger is pressed
  70864. * @param callback defines the callback to use
  70865. */
  70866. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70867. this._onrighttriggerchanged = callback;
  70868. };
  70869. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70870. /**
  70871. * Gets or sets left trigger value
  70872. */
  70873. get: function () {
  70874. return this._leftTrigger;
  70875. },
  70876. set: function (newValue) {
  70877. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70878. this._onlefttriggerchanged(newValue);
  70879. }
  70880. this._leftTrigger = newValue;
  70881. },
  70882. enumerable: true,
  70883. configurable: true
  70884. });
  70885. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70886. /**
  70887. * Gets or sets right trigger value
  70888. */
  70889. get: function () {
  70890. return this._rightTrigger;
  70891. },
  70892. set: function (newValue) {
  70893. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70894. this._onrighttriggerchanged(newValue);
  70895. }
  70896. this._rightTrigger = newValue;
  70897. },
  70898. enumerable: true,
  70899. configurable: true
  70900. });
  70901. /**
  70902. * Defines the callback to call when a button is pressed
  70903. * @param callback defines the callback to use
  70904. */
  70905. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70906. this._onbuttondown = callback;
  70907. };
  70908. /**
  70909. * Defines the callback to call when a button is released
  70910. * @param callback defines the callback to use
  70911. */
  70912. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70913. this._onbuttonup = callback;
  70914. };
  70915. /**
  70916. * Defines the callback to call when a pad is pressed
  70917. * @param callback defines the callback to use
  70918. */
  70919. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70920. this._ondpaddown = callback;
  70921. };
  70922. /**
  70923. * Defines the callback to call when a pad is released
  70924. * @param callback defines the callback to use
  70925. */
  70926. Xbox360Pad.prototype.ondpadup = function (callback) {
  70927. this._ondpadup = callback;
  70928. };
  70929. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70930. if (newValue !== currentValue) {
  70931. if (newValue === 1) {
  70932. if (this._onbuttondown) {
  70933. this._onbuttondown(buttonType);
  70934. }
  70935. this.onButtonDownObservable.notifyObservers(buttonType);
  70936. }
  70937. if (newValue === 0) {
  70938. if (this._onbuttonup) {
  70939. this._onbuttonup(buttonType);
  70940. }
  70941. this.onButtonUpObservable.notifyObservers(buttonType);
  70942. }
  70943. }
  70944. return newValue;
  70945. };
  70946. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70947. if (newValue !== currentValue) {
  70948. if (newValue === 1) {
  70949. if (this._ondpaddown) {
  70950. this._ondpaddown(buttonType);
  70951. }
  70952. this.onPadDownObservable.notifyObservers(buttonType);
  70953. }
  70954. if (newValue === 0) {
  70955. if (this._ondpadup) {
  70956. this._ondpadup(buttonType);
  70957. }
  70958. this.onPadUpObservable.notifyObservers(buttonType);
  70959. }
  70960. }
  70961. return newValue;
  70962. };
  70963. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70964. /** Gets or sets value of A button */
  70965. get: function () {
  70966. return this._buttonA;
  70967. },
  70968. set: function (value) {
  70969. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70970. },
  70971. enumerable: true,
  70972. configurable: true
  70973. });
  70974. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70975. /** Gets or sets value of B button */
  70976. get: function () {
  70977. return this._buttonB;
  70978. },
  70979. set: function (value) {
  70980. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70981. },
  70982. enumerable: true,
  70983. configurable: true
  70984. });
  70985. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70986. /** Gets or sets value of X button */
  70987. get: function () {
  70988. return this._buttonX;
  70989. },
  70990. set: function (value) {
  70991. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70992. },
  70993. enumerable: true,
  70994. configurable: true
  70995. });
  70996. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70997. /** Gets or sets value of Y button */
  70998. get: function () {
  70999. return this._buttonY;
  71000. },
  71001. set: function (value) {
  71002. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71003. },
  71004. enumerable: true,
  71005. configurable: true
  71006. });
  71007. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71008. /** Gets or sets value of Start button */
  71009. get: function () {
  71010. return this._buttonStart;
  71011. },
  71012. set: function (value) {
  71013. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71014. },
  71015. enumerable: true,
  71016. configurable: true
  71017. });
  71018. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71019. /** Gets or sets value of Back button */
  71020. get: function () {
  71021. return this._buttonBack;
  71022. },
  71023. set: function (value) {
  71024. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71025. },
  71026. enumerable: true,
  71027. configurable: true
  71028. });
  71029. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71030. /** Gets or sets value of Left button */
  71031. get: function () {
  71032. return this._buttonLB;
  71033. },
  71034. set: function (value) {
  71035. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71036. },
  71037. enumerable: true,
  71038. configurable: true
  71039. });
  71040. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71041. /** Gets or sets value of Right button */
  71042. get: function () {
  71043. return this._buttonRB;
  71044. },
  71045. set: function (value) {
  71046. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71047. },
  71048. enumerable: true,
  71049. configurable: true
  71050. });
  71051. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71052. /** Gets or sets value of left stick */
  71053. get: function () {
  71054. return this._buttonLeftStick;
  71055. },
  71056. set: function (value) {
  71057. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71058. },
  71059. enumerable: true,
  71060. configurable: true
  71061. });
  71062. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71063. /** Gets or sets value of right stick */
  71064. get: function () {
  71065. return this._buttonRightStick;
  71066. },
  71067. set: function (value) {
  71068. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71069. },
  71070. enumerable: true,
  71071. configurable: true
  71072. });
  71073. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71074. /** Gets or sets value of DPad up */
  71075. get: function () {
  71076. return this._dPadUp;
  71077. },
  71078. set: function (value) {
  71079. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71080. },
  71081. enumerable: true,
  71082. configurable: true
  71083. });
  71084. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71085. /** Gets or sets value of DPad down */
  71086. get: function () {
  71087. return this._dPadDown;
  71088. },
  71089. set: function (value) {
  71090. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71091. },
  71092. enumerable: true,
  71093. configurable: true
  71094. });
  71095. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71096. /** Gets or sets value of DPad left */
  71097. get: function () {
  71098. return this._dPadLeft;
  71099. },
  71100. set: function (value) {
  71101. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71102. },
  71103. enumerable: true,
  71104. configurable: true
  71105. });
  71106. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71107. /** Gets or sets value of DPad right */
  71108. get: function () {
  71109. return this._dPadRight;
  71110. },
  71111. set: function (value) {
  71112. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71113. },
  71114. enumerable: true,
  71115. configurable: true
  71116. });
  71117. /**
  71118. * Force the gamepad to synchronize with device values
  71119. */
  71120. Xbox360Pad.prototype.update = function () {
  71121. _super.prototype.update.call(this);
  71122. if (this._isXboxOnePad) {
  71123. this.buttonA = this.browserGamepad.buttons[0].value;
  71124. this.buttonB = this.browserGamepad.buttons[1].value;
  71125. this.buttonX = this.browserGamepad.buttons[2].value;
  71126. this.buttonY = this.browserGamepad.buttons[3].value;
  71127. this.buttonLB = this.browserGamepad.buttons[4].value;
  71128. this.buttonRB = this.browserGamepad.buttons[5].value;
  71129. this.leftTrigger = this.browserGamepad.axes[2];
  71130. this.rightTrigger = this.browserGamepad.axes[5];
  71131. this.buttonBack = this.browserGamepad.buttons[9].value;
  71132. this.buttonStart = this.browserGamepad.buttons[8].value;
  71133. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71134. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71135. this.dPadUp = this.browserGamepad.buttons[11].value;
  71136. this.dPadDown = this.browserGamepad.buttons[12].value;
  71137. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71138. this.dPadRight = this.browserGamepad.buttons[14].value;
  71139. }
  71140. else {
  71141. this.buttonA = this.browserGamepad.buttons[0].value;
  71142. this.buttonB = this.browserGamepad.buttons[1].value;
  71143. this.buttonX = this.browserGamepad.buttons[2].value;
  71144. this.buttonY = this.browserGamepad.buttons[3].value;
  71145. this.buttonLB = this.browserGamepad.buttons[4].value;
  71146. this.buttonRB = this.browserGamepad.buttons[5].value;
  71147. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71148. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71149. this.buttonBack = this.browserGamepad.buttons[8].value;
  71150. this.buttonStart = this.browserGamepad.buttons[9].value;
  71151. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71152. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71153. this.dPadUp = this.browserGamepad.buttons[12].value;
  71154. this.dPadDown = this.browserGamepad.buttons[13].value;
  71155. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71156. this.dPadRight = this.browserGamepad.buttons[15].value;
  71157. }
  71158. };
  71159. Xbox360Pad.prototype.dispose = function () {
  71160. _super.prototype.dispose.call(this);
  71161. this.onButtonDownObservable.clear();
  71162. this.onButtonUpObservable.clear();
  71163. this.onPadDownObservable.clear();
  71164. this.onPadUpObservable.clear();
  71165. };
  71166. return Xbox360Pad;
  71167. }(BABYLON.Gamepad));
  71168. BABYLON.Xbox360Pad = Xbox360Pad;
  71169. })(BABYLON || (BABYLON = {}));
  71170. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71171. var BABYLON;
  71172. (function (BABYLON) {
  71173. /**
  71174. * Defines the types of pose enabled controllers that are supported
  71175. */
  71176. var PoseEnabledControllerType;
  71177. (function (PoseEnabledControllerType) {
  71178. /**
  71179. * HTC Vive
  71180. */
  71181. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71182. /**
  71183. * Oculus Rift
  71184. */
  71185. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71186. /**
  71187. * Windows mixed reality
  71188. */
  71189. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71190. /**
  71191. * Samsung gear VR
  71192. */
  71193. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71194. /**
  71195. * Google Daydream
  71196. */
  71197. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71198. /**
  71199. * Generic
  71200. */
  71201. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71202. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71203. /**
  71204. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71205. */
  71206. var PoseEnabledControllerHelper = /** @class */ (function () {
  71207. function PoseEnabledControllerHelper() {
  71208. }
  71209. /**
  71210. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71211. * @param vrGamepad the gamepad to initialized
  71212. * @returns a vr controller of the type the gamepad identified as
  71213. */
  71214. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71215. // Oculus Touch
  71216. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71217. return new BABYLON.OculusTouchController(vrGamepad);
  71218. }
  71219. // Windows Mixed Reality controllers
  71220. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71221. return new BABYLON.WindowsMotionController(vrGamepad);
  71222. }
  71223. // HTC Vive
  71224. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71225. return new BABYLON.ViveController(vrGamepad);
  71226. }
  71227. // Samsung/Oculus Gear VR or Oculus Go
  71228. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71229. return new BABYLON.GearVRController(vrGamepad);
  71230. }
  71231. // Google Daydream
  71232. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71233. return new BABYLON.DaydreamController(vrGamepad);
  71234. }
  71235. // Generic
  71236. else {
  71237. return new BABYLON.GenericController(vrGamepad);
  71238. }
  71239. };
  71240. return PoseEnabledControllerHelper;
  71241. }());
  71242. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71243. /**
  71244. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71245. */
  71246. var PoseEnabledController = /** @class */ (function (_super) {
  71247. __extends(PoseEnabledController, _super);
  71248. /**
  71249. * Creates a new PoseEnabledController from a gamepad
  71250. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71251. */
  71252. function PoseEnabledController(browserGamepad) {
  71253. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71254. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71255. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71256. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71257. /**
  71258. * The device position in babylon space
  71259. */
  71260. _this.devicePosition = BABYLON.Vector3.Zero();
  71261. /**
  71262. * The device rotation in babylon space
  71263. */
  71264. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71265. /**
  71266. * The scale factor of the device in babylon space
  71267. */
  71268. _this.deviceScaleFactor = 1;
  71269. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71270. /**
  71271. * Internal, matrix used to convert room space to babylon space
  71272. */
  71273. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71274. /**
  71275. * Node to be used when casting a ray from the controller
  71276. */
  71277. _this._pointingPoseNode = null;
  71278. _this._workingMatrix = BABYLON.Matrix.Identity();
  71279. /**
  71280. * @hidden
  71281. */
  71282. _this._meshAttachedObservable = new BABYLON.Observable();
  71283. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71284. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71285. _this.position = BABYLON.Vector3.Zero();
  71286. _this.rotationQuaternion = new BABYLON.Quaternion();
  71287. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71288. _this._calculatedRotation = new BABYLON.Quaternion();
  71289. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71290. return _this;
  71291. }
  71292. /**
  71293. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71294. */
  71295. PoseEnabledController.prototype.update = function () {
  71296. _super.prototype.update.call(this);
  71297. var pose = this.browserGamepad.pose;
  71298. this.updateFromDevice(pose);
  71299. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71300. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71301. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71302. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71303. if (this._mesh) {
  71304. this._mesh.position.copyFrom(this.devicePosition);
  71305. if (this._mesh.rotationQuaternion) {
  71306. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71307. }
  71308. }
  71309. };
  71310. /**
  71311. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71312. * @param poseData raw pose fromthe device
  71313. */
  71314. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71315. if (poseData) {
  71316. this.rawPose = poseData;
  71317. if (poseData.position) {
  71318. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71319. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71320. this._deviceRoomPosition.z *= -1;
  71321. }
  71322. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71323. this._calculatedPosition.addInPlace(this.position);
  71324. }
  71325. var pose = this.rawPose;
  71326. if (poseData.orientation && pose.orientation) {
  71327. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71328. if (this._mesh) {
  71329. if (this._mesh.getScene().useRightHandedSystem) {
  71330. this._deviceRoomRotationQuaternion.z *= -1;
  71331. this._deviceRoomRotationQuaternion.w *= -1;
  71332. }
  71333. else {
  71334. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71335. }
  71336. }
  71337. // if the camera is set, rotate to the camera's rotation
  71338. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71339. }
  71340. }
  71341. };
  71342. /**
  71343. * Attaches a mesh to the controller
  71344. * @param mesh the mesh to be attached
  71345. */
  71346. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71347. if (this._mesh) {
  71348. this._mesh.parent = null;
  71349. }
  71350. this._mesh = mesh;
  71351. if (this._poseControlledCamera) {
  71352. this._mesh.parent = this._poseControlledCamera;
  71353. }
  71354. if (!this._mesh.rotationQuaternion) {
  71355. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71356. }
  71357. // Sync controller mesh and pointing pose node's state with controller
  71358. this.update();
  71359. if (this._pointingPoseNode) {
  71360. var parents = [];
  71361. var obj = this._pointingPoseNode;
  71362. while (obj.parent) {
  71363. parents.push(obj.parent);
  71364. obj = obj.parent;
  71365. }
  71366. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71367. }
  71368. this._meshAttachedObservable.notifyObservers(mesh);
  71369. };
  71370. /**
  71371. * Attaches the controllers mesh to a camera
  71372. * @param camera the camera the mesh should be attached to
  71373. */
  71374. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71375. this._poseControlledCamera = camera;
  71376. if (this._mesh) {
  71377. this._mesh.parent = this._poseControlledCamera;
  71378. }
  71379. };
  71380. /**
  71381. * Disposes of the controller
  71382. */
  71383. PoseEnabledController.prototype.dispose = function () {
  71384. if (this._mesh) {
  71385. this._mesh.dispose();
  71386. }
  71387. this._mesh = null;
  71388. _super.prototype.dispose.call(this);
  71389. };
  71390. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71391. /**
  71392. * The mesh that is attached to the controller
  71393. */
  71394. get: function () {
  71395. return this._mesh;
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. /**
  71401. * Gets the ray of the controller in the direction the controller is pointing
  71402. * @param length the length the resulting ray should be
  71403. * @returns a ray in the direction the controller is pointing
  71404. */
  71405. PoseEnabledController.prototype.getForwardRay = function (length) {
  71406. if (length === void 0) { length = 100; }
  71407. if (!this.mesh) {
  71408. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71409. }
  71410. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71411. var origin = m.getTranslation();
  71412. var forward = new BABYLON.Vector3(0, 0, -1);
  71413. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71414. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71415. return new BABYLON.Ray(origin, direction, length);
  71416. };
  71417. /**
  71418. * Name of the child mesh that can be used to cast a ray from the controller
  71419. */
  71420. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71421. return PoseEnabledController;
  71422. }(BABYLON.Gamepad));
  71423. BABYLON.PoseEnabledController = PoseEnabledController;
  71424. })(BABYLON || (BABYLON = {}));
  71425. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71426. var BABYLON;
  71427. (function (BABYLON) {
  71428. /**
  71429. * Defines the WebVRController object that represents controllers tracked in 3D space
  71430. */
  71431. var WebVRController = /** @class */ (function (_super) {
  71432. __extends(WebVRController, _super);
  71433. /**
  71434. * Creates a new WebVRController from a gamepad
  71435. * @param vrGamepad the gamepad that the WebVRController should be created from
  71436. */
  71437. function WebVRController(vrGamepad) {
  71438. var _this = _super.call(this, vrGamepad) || this;
  71439. // Observables
  71440. /**
  71441. * Fired when the trigger state has changed
  71442. */
  71443. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71444. /**
  71445. * Fired when the main button state has changed
  71446. */
  71447. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71448. /**
  71449. * Fired when the secondary button state has changed
  71450. */
  71451. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71452. /**
  71453. * Fired when the pad state has changed
  71454. */
  71455. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71456. /**
  71457. * Fired when controllers stick values have changed
  71458. */
  71459. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71460. /**
  71461. * X and Y axis corrisponding to the controllers joystick
  71462. */
  71463. _this.pad = { x: 0, y: 0 };
  71464. // avoid GC, store state in a tmp object
  71465. _this._changes = {
  71466. pressChanged: false,
  71467. touchChanged: false,
  71468. valueChanged: false,
  71469. changed: false
  71470. };
  71471. _this._buttons = new Array(vrGamepad.buttons.length);
  71472. _this.hand = vrGamepad.hand;
  71473. return _this;
  71474. }
  71475. /**
  71476. * Fired when a controller button's state has changed
  71477. * @param callback the callback containing the button that was modified
  71478. */
  71479. WebVRController.prototype.onButtonStateChange = function (callback) {
  71480. this._onButtonStateChange = callback;
  71481. };
  71482. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71483. /**
  71484. * The default controller model for the controller
  71485. */
  71486. get: function () {
  71487. return this._defaultModel;
  71488. },
  71489. enumerable: true,
  71490. configurable: true
  71491. });
  71492. /**
  71493. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71494. */
  71495. WebVRController.prototype.update = function () {
  71496. _super.prototype.update.call(this);
  71497. for (var index = 0; index < this._buttons.length; index++) {
  71498. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71499. }
  71500. ;
  71501. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71502. this.pad.x = this.leftStick.x;
  71503. this.pad.y = this.leftStick.y;
  71504. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71505. }
  71506. };
  71507. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71508. if (!newState) {
  71509. newState = {
  71510. pressed: false,
  71511. touched: false,
  71512. value: 0
  71513. };
  71514. }
  71515. if (!currentState) {
  71516. this._buttons[buttonIndex] = {
  71517. pressed: newState.pressed,
  71518. touched: newState.touched,
  71519. value: newState.value
  71520. };
  71521. return;
  71522. }
  71523. this._checkChanges(newState, currentState);
  71524. if (this._changes.changed) {
  71525. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71526. this._handleButtonChange(buttonIndex, newState, this._changes);
  71527. }
  71528. this._buttons[buttonIndex].pressed = newState.pressed;
  71529. this._buttons[buttonIndex].touched = newState.touched;
  71530. // oculus triggers are never 0, thou not touched.
  71531. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71532. };
  71533. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71534. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71535. this._changes.touchChanged = newState.touched !== currentState.touched;
  71536. this._changes.valueChanged = newState.value !== currentState.value;
  71537. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71538. return this._changes;
  71539. };
  71540. /**
  71541. * Disposes of th webVRCOntroller
  71542. */
  71543. WebVRController.prototype.dispose = function () {
  71544. _super.prototype.dispose.call(this);
  71545. this.onTriggerStateChangedObservable.clear();
  71546. this.onMainButtonStateChangedObservable.clear();
  71547. this.onSecondaryButtonStateChangedObservable.clear();
  71548. this.onPadStateChangedObservable.clear();
  71549. this.onPadValuesChangedObservable.clear();
  71550. };
  71551. return WebVRController;
  71552. }(BABYLON.PoseEnabledController));
  71553. BABYLON.WebVRController = WebVRController;
  71554. })(BABYLON || (BABYLON = {}));
  71555. //# sourceMappingURL=babylon.webVRController.js.map
  71556. var BABYLON;
  71557. (function (BABYLON) {
  71558. /**
  71559. * Oculus Touch Controller
  71560. */
  71561. var OculusTouchController = /** @class */ (function (_super) {
  71562. __extends(OculusTouchController, _super);
  71563. /**
  71564. * Creates a new OculusTouchController from a gamepad
  71565. * @param vrGamepad the gamepad that the controller should be created from
  71566. */
  71567. function OculusTouchController(vrGamepad) {
  71568. var _this = _super.call(this, vrGamepad) || this;
  71569. /**
  71570. * Fired when the secondary trigger on this controller is modified
  71571. */
  71572. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71573. /**
  71574. * Fired when the thumb rest on this controller is modified
  71575. */
  71576. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71577. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71578. return _this;
  71579. }
  71580. /**
  71581. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71582. * @param scene scene in which to add meshes
  71583. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71584. */
  71585. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71586. var _this = this;
  71587. var meshName;
  71588. // Hand
  71589. if (this.hand === 'left') {
  71590. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71591. }
  71592. else { // Right is the default if no hand is specified
  71593. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71594. }
  71595. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71596. /*
  71597. Parent Mesh name: oculus_touch_left
  71598. - body
  71599. - trigger
  71600. - thumbstick
  71601. - grip
  71602. - button_y
  71603. - button_x
  71604. - button_enter
  71605. */
  71606. _this._defaultModel = newMeshes[1];
  71607. _this.attachToMesh(_this._defaultModel);
  71608. if (meshLoaded) {
  71609. meshLoaded(_this._defaultModel);
  71610. }
  71611. });
  71612. };
  71613. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71614. /**
  71615. * Fired when the A button on this controller is modified
  71616. */
  71617. get: function () {
  71618. if (this.hand === 'right') {
  71619. return this.onMainButtonStateChangedObservable;
  71620. }
  71621. else {
  71622. throw new Error('No A button on left hand');
  71623. }
  71624. },
  71625. enumerable: true,
  71626. configurable: true
  71627. });
  71628. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71629. /**
  71630. * Fired when the B button on this controller is modified
  71631. */
  71632. get: function () {
  71633. if (this.hand === 'right') {
  71634. return this.onSecondaryButtonStateChangedObservable;
  71635. }
  71636. else {
  71637. throw new Error('No B button on left hand');
  71638. }
  71639. },
  71640. enumerable: true,
  71641. configurable: true
  71642. });
  71643. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71644. /**
  71645. * Fired when the X button on this controller is modified
  71646. */
  71647. get: function () {
  71648. if (this.hand === 'left') {
  71649. return this.onMainButtonStateChangedObservable;
  71650. }
  71651. else {
  71652. throw new Error('No X button on right hand');
  71653. }
  71654. },
  71655. enumerable: true,
  71656. configurable: true
  71657. });
  71658. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71659. /**
  71660. * Fired when the Y button on this controller is modified
  71661. */
  71662. get: function () {
  71663. if (this.hand === 'left') {
  71664. return this.onSecondaryButtonStateChangedObservable;
  71665. }
  71666. else {
  71667. throw new Error('No Y button on right hand');
  71668. }
  71669. },
  71670. enumerable: true,
  71671. configurable: true
  71672. });
  71673. /**
  71674. * Called once for each button that changed state since the last frame
  71675. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71676. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71677. * 2) secondary trigger (same)
  71678. * 3) A (right) X (left), touch, pressed = value
  71679. * 4) B / Y
  71680. * 5) thumb rest
  71681. * @param buttonIdx Which button index changed
  71682. * @param state New state of the button
  71683. * @param changes Which properties on the state changed since last frame
  71684. */
  71685. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71686. var notifyObject = state; //{ state: state, changes: changes };
  71687. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71688. switch (buttonIdx) {
  71689. case 0:
  71690. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71691. return;
  71692. case 1: // index trigger
  71693. if (this._defaultModel) {
  71694. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71695. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71696. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71697. }
  71698. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71699. return;
  71700. case 2: // secondary trigger
  71701. if (this._defaultModel) {
  71702. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71703. }
  71704. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71705. return;
  71706. case 3:
  71707. if (this._defaultModel) {
  71708. if (notifyObject.pressed) {
  71709. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71710. }
  71711. else {
  71712. (this._defaultModel.getChildren()[1]).position.y = 0;
  71713. }
  71714. }
  71715. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71716. return;
  71717. case 4:
  71718. if (this._defaultModel) {
  71719. if (notifyObject.pressed) {
  71720. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71721. }
  71722. else {
  71723. (this._defaultModel.getChildren()[2]).position.y = 0;
  71724. }
  71725. }
  71726. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71727. return;
  71728. case 5:
  71729. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71730. return;
  71731. }
  71732. };
  71733. /**
  71734. * Base Url for the controller model.
  71735. */
  71736. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71737. /**
  71738. * File name for the left controller model.
  71739. */
  71740. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71741. /**
  71742. * File name for the right controller model.
  71743. */
  71744. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71745. return OculusTouchController;
  71746. }(BABYLON.WebVRController));
  71747. BABYLON.OculusTouchController = OculusTouchController;
  71748. })(BABYLON || (BABYLON = {}));
  71749. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71750. var BABYLON;
  71751. (function (BABYLON) {
  71752. /**
  71753. * Vive Controller
  71754. */
  71755. var ViveController = /** @class */ (function (_super) {
  71756. __extends(ViveController, _super);
  71757. /**
  71758. * Creates a new ViveController from a gamepad
  71759. * @param vrGamepad the gamepad that the controller should be created from
  71760. */
  71761. function ViveController(vrGamepad) {
  71762. var _this = _super.call(this, vrGamepad) || this;
  71763. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71764. _this._invertLeftStickY = true;
  71765. return _this;
  71766. }
  71767. /**
  71768. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71769. * @param scene scene in which to add meshes
  71770. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71771. */
  71772. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71773. var _this = this;
  71774. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71775. /*
  71776. Parent Mesh name: ViveWand
  71777. - body
  71778. - r_gripper
  71779. - l_gripper
  71780. - menu_button
  71781. - system_button
  71782. - trackpad
  71783. - trigger
  71784. - LED
  71785. */
  71786. _this._defaultModel = newMeshes[1];
  71787. _this.attachToMesh(_this._defaultModel);
  71788. if (meshLoaded) {
  71789. meshLoaded(_this._defaultModel);
  71790. }
  71791. });
  71792. };
  71793. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71794. /**
  71795. * Fired when the left button on this controller is modified
  71796. */
  71797. get: function () {
  71798. return this.onMainButtonStateChangedObservable;
  71799. },
  71800. enumerable: true,
  71801. configurable: true
  71802. });
  71803. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71804. /**
  71805. * Fired when the right button on this controller is modified
  71806. */
  71807. get: function () {
  71808. return this.onMainButtonStateChangedObservable;
  71809. },
  71810. enumerable: true,
  71811. configurable: true
  71812. });
  71813. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71814. /**
  71815. * Fired when the menu button on this controller is modified
  71816. */
  71817. get: function () {
  71818. return this.onSecondaryButtonStateChangedObservable;
  71819. },
  71820. enumerable: true,
  71821. configurable: true
  71822. });
  71823. /**
  71824. * Called once for each button that changed state since the last frame
  71825. * Vive mapping:
  71826. * 0: touchpad
  71827. * 1: trigger
  71828. * 2: left AND right buttons
  71829. * 3: menu button
  71830. * @param buttonIdx Which button index changed
  71831. * @param state New state of the button
  71832. * @param changes Which properties on the state changed since last frame
  71833. */
  71834. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71835. var notifyObject = state; //{ state: state, changes: changes };
  71836. switch (buttonIdx) {
  71837. case 0:
  71838. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71839. return;
  71840. case 1: // index trigger
  71841. if (this._defaultModel) {
  71842. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71843. }
  71844. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71845. return;
  71846. case 2: // left AND right button
  71847. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71848. return;
  71849. case 3:
  71850. if (this._defaultModel) {
  71851. if (notifyObject.pressed) {
  71852. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71853. }
  71854. else {
  71855. (this._defaultModel.getChildren()[2]).position.y = 0;
  71856. }
  71857. }
  71858. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71859. return;
  71860. }
  71861. };
  71862. /**
  71863. * Base Url for the controller model.
  71864. */
  71865. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71866. /**
  71867. * File name for the controller model.
  71868. */
  71869. ViveController.MODEL_FILENAME = 'wand.babylon';
  71870. return ViveController;
  71871. }(BABYLON.WebVRController));
  71872. BABYLON.ViveController = ViveController;
  71873. })(BABYLON || (BABYLON = {}));
  71874. //# sourceMappingURL=babylon.viveController.js.map
  71875. var BABYLON;
  71876. (function (BABYLON) {
  71877. /**
  71878. * Generic Controller
  71879. */
  71880. var GenericController = /** @class */ (function (_super) {
  71881. __extends(GenericController, _super);
  71882. /**
  71883. * Creates a new GenericController from a gamepad
  71884. * @param vrGamepad the gamepad that the controller should be created from
  71885. */
  71886. function GenericController(vrGamepad) {
  71887. return _super.call(this, vrGamepad) || this;
  71888. }
  71889. /**
  71890. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71891. * @param scene scene in which to add meshes
  71892. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71893. */
  71894. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71895. var _this = this;
  71896. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71897. _this._defaultModel = newMeshes[1];
  71898. _this.attachToMesh(_this._defaultModel);
  71899. if (meshLoaded) {
  71900. meshLoaded(_this._defaultModel);
  71901. }
  71902. });
  71903. };
  71904. /**
  71905. * Called once for each button that changed state since the last frame
  71906. * @param buttonIdx Which button index changed
  71907. * @param state New state of the button
  71908. * @param changes Which properties on the state changed since last frame
  71909. */
  71910. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71911. console.log("Button id: " + buttonIdx + "state: ");
  71912. console.dir(state);
  71913. };
  71914. /**
  71915. * Base Url for the controller model.
  71916. */
  71917. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71918. /**
  71919. * File name for the controller model.
  71920. */
  71921. GenericController.MODEL_FILENAME = 'generic.babylon';
  71922. return GenericController;
  71923. }(BABYLON.WebVRController));
  71924. BABYLON.GenericController = GenericController;
  71925. })(BABYLON || (BABYLON = {}));
  71926. //# sourceMappingURL=babylon.genericController.js.map
  71927. var BABYLON;
  71928. (function (BABYLON) {
  71929. /**
  71930. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71931. */
  71932. var LoadedMeshInfo = /** @class */ (function () {
  71933. function LoadedMeshInfo() {
  71934. /**
  71935. * Map of the button meshes contained in the controller
  71936. */
  71937. this.buttonMeshes = {};
  71938. /**
  71939. * Map of the axis meshes contained in the controller
  71940. */
  71941. this.axisMeshes = {};
  71942. }
  71943. return LoadedMeshInfo;
  71944. }());
  71945. /**
  71946. * Defines the WindowsMotionController object that the state of the windows motion controller
  71947. */
  71948. var WindowsMotionController = /** @class */ (function (_super) {
  71949. __extends(WindowsMotionController, _super);
  71950. /**
  71951. * Creates a new WindowsMotionController from a gamepad
  71952. * @param vrGamepad the gamepad that the controller should be created from
  71953. */
  71954. function WindowsMotionController(vrGamepad) {
  71955. var _this = _super.call(this, vrGamepad) || this;
  71956. _this._mapping = {
  71957. // Semantic button names
  71958. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71959. // A mapping of the button name to glTF model node name
  71960. // that should be transformed by button value.
  71961. buttonMeshNames: {
  71962. 'trigger': 'SELECT',
  71963. 'menu': 'MENU',
  71964. 'grip': 'GRASP',
  71965. 'thumbstick': 'THUMBSTICK_PRESS',
  71966. 'trackpad': 'TOUCHPAD_PRESS'
  71967. },
  71968. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71969. buttonObservableNames: {
  71970. 'trigger': 'onTriggerStateChangedObservable',
  71971. 'menu': 'onSecondaryButtonStateChangedObservable',
  71972. 'grip': 'onMainButtonStateChangedObservable',
  71973. 'thumbstick': 'onPadStateChangedObservable',
  71974. 'trackpad': 'onTrackpadChangedObservable'
  71975. },
  71976. // A mapping of the axis name to glTF model node name
  71977. // that should be transformed by axis value.
  71978. // This array mirrors the browserGamepad.axes array, such that
  71979. // the mesh corresponding to axis 0 is in this array index 0.
  71980. axisMeshNames: [
  71981. 'THUMBSTICK_X',
  71982. 'THUMBSTICK_Y',
  71983. 'TOUCHPAD_TOUCH_X',
  71984. 'TOUCHPAD_TOUCH_Y'
  71985. ],
  71986. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71987. };
  71988. /**
  71989. * Fired when the trackpad on this controller is clicked
  71990. */
  71991. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71992. /**
  71993. * Fired when the trackpad on this controller is modified
  71994. */
  71995. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71996. /**
  71997. * The current x and y values of this controller's trackpad
  71998. */
  71999. _this.trackpad = { x: 0, y: 0 };
  72000. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72001. _this._loadedMeshInfo = null;
  72002. return _this;
  72003. }
  72004. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72005. /**
  72006. * Fired when the trigger on this controller is modified
  72007. */
  72008. get: function () {
  72009. return this.onTriggerStateChangedObservable;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72015. /**
  72016. * Fired when the menu button on this controller is modified
  72017. */
  72018. get: function () {
  72019. return this.onSecondaryButtonStateChangedObservable;
  72020. },
  72021. enumerable: true,
  72022. configurable: true
  72023. });
  72024. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72025. /**
  72026. * Fired when the grip button on this controller is modified
  72027. */
  72028. get: function () {
  72029. return this.onMainButtonStateChangedObservable;
  72030. },
  72031. enumerable: true,
  72032. configurable: true
  72033. });
  72034. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72035. /**
  72036. * Fired when the thumbstick button on this controller is modified
  72037. */
  72038. get: function () {
  72039. return this.onPadStateChangedObservable;
  72040. },
  72041. enumerable: true,
  72042. configurable: true
  72043. });
  72044. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72045. /**
  72046. * Fired when the touchpad button on this controller is modified
  72047. */
  72048. get: function () {
  72049. return this.onTrackpadChangedObservable;
  72050. },
  72051. enumerable: true,
  72052. configurable: true
  72053. });
  72054. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72055. /**
  72056. * Fired when the touchpad values on this controller are modified
  72057. */
  72058. get: function () {
  72059. return this.onTrackpadValuesChangedObservable;
  72060. },
  72061. enumerable: true,
  72062. configurable: true
  72063. });
  72064. WindowsMotionController.prototype._updateTrackpad = function () {
  72065. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72066. this.trackpad.x = this.browserGamepad["axes"][2];
  72067. this.trackpad.y = this.browserGamepad["axes"][3];
  72068. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72069. }
  72070. };
  72071. /**
  72072. * Called once per frame by the engine.
  72073. */
  72074. WindowsMotionController.prototype.update = function () {
  72075. _super.prototype.update.call(this);
  72076. if (this.browserGamepad.axes) {
  72077. this._updateTrackpad();
  72078. // Only need to animate axes if there is a loaded mesh
  72079. if (this._loadedMeshInfo) {
  72080. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72081. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72082. }
  72083. }
  72084. }
  72085. };
  72086. /**
  72087. * Called once for each button that changed state since the last frame
  72088. * @param buttonIdx Which button index changed
  72089. * @param state New state of the button
  72090. * @param changes Which properties on the state changed since last frame
  72091. */
  72092. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72093. var buttonName = this._mapping.buttons[buttonIdx];
  72094. if (!buttonName) {
  72095. return;
  72096. }
  72097. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72098. this._updateTrackpad();
  72099. // Only emit events for buttons that we know how to map from index to name
  72100. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72101. if (observable) {
  72102. observable.notifyObservers(state);
  72103. }
  72104. this._lerpButtonTransform(buttonName, state.value);
  72105. };
  72106. /**
  72107. * Moves the buttons on the controller mesh based on their current state
  72108. * @param buttonName the name of the button to move
  72109. * @param buttonValue the value of the button which determines the buttons new position
  72110. */
  72111. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72112. // If there is no loaded mesh, there is nothing to transform.
  72113. if (!this._loadedMeshInfo) {
  72114. return;
  72115. }
  72116. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72117. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72118. return;
  72119. }
  72120. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72121. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72122. };
  72123. /**
  72124. * Moves the axis on the controller mesh based on its current state
  72125. * @param axis the index of the axis
  72126. * @param axisValue the value of the axis which determines the meshes new position
  72127. * @hidden
  72128. */
  72129. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72130. if (!this._loadedMeshInfo) {
  72131. return;
  72132. }
  72133. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72134. if (!meshInfo) {
  72135. return;
  72136. }
  72137. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72138. return;
  72139. }
  72140. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72141. var lerpValue = axisValue * 0.5 + 0.5;
  72142. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72143. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72144. };
  72145. /**
  72146. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72147. * @param scene scene in which to add meshes
  72148. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72149. */
  72150. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72151. var _this = this;
  72152. if (forceDefault === void 0) { forceDefault = false; }
  72153. var path;
  72154. var filename;
  72155. // Checking if GLB loader is present
  72156. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72157. // Determine the device specific folder based on the ID suffix
  72158. var device = 'default';
  72159. if (this.id && !forceDefault) {
  72160. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72161. device = ((match && match[0]) || device);
  72162. }
  72163. // Hand
  72164. if (this.hand === 'left') {
  72165. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72166. }
  72167. else { // Right is the default if no hand is specified
  72168. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72169. }
  72170. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72171. }
  72172. else {
  72173. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72174. path = BABYLON.GenericController.MODEL_BASE_URL;
  72175. filename = BABYLON.GenericController.MODEL_FILENAME;
  72176. }
  72177. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72178. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72179. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72180. if (!_this._loadedMeshInfo) {
  72181. return;
  72182. }
  72183. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72184. _this.attachToMesh(_this._defaultModel);
  72185. if (meshLoaded) {
  72186. meshLoaded(_this._defaultModel);
  72187. }
  72188. }, null, function (scene, message) {
  72189. BABYLON.Tools.Log(message);
  72190. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72191. if (!forceDefault) {
  72192. _this.initControllerMesh(scene, meshLoaded, true);
  72193. }
  72194. });
  72195. };
  72196. /**
  72197. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72198. * can be transformed by button presses and axes values, based on this._mapping.
  72199. *
  72200. * @param scene scene in which the meshes exist
  72201. * @param meshes list of meshes that make up the controller model to process
  72202. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72203. */
  72204. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72205. var loadedMeshInfo = null;
  72206. // Create a new mesh to contain the glTF hierarchy
  72207. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72208. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72209. var childMesh = null;
  72210. for (var i = 0; i < meshes.length; i++) {
  72211. var mesh = meshes[i];
  72212. if (!mesh.parent) {
  72213. // Exclude controller meshes from picking results
  72214. mesh.isPickable = false;
  72215. // Handle root node, attach to the new parentMesh
  72216. childMesh = mesh;
  72217. break;
  72218. }
  72219. }
  72220. if (childMesh) {
  72221. childMesh.setParent(parentMesh);
  72222. // Create our mesh info. Note that this method will always return non-null.
  72223. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72224. }
  72225. else {
  72226. BABYLON.Tools.Warn('Could not find root node in model file.');
  72227. }
  72228. return loadedMeshInfo;
  72229. };
  72230. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72231. var loadedMeshInfo = new LoadedMeshInfo();
  72232. var i;
  72233. loadedMeshInfo.rootNode = rootNode;
  72234. // Reset the caches
  72235. loadedMeshInfo.buttonMeshes = {};
  72236. loadedMeshInfo.axisMeshes = {};
  72237. // Button Meshes
  72238. for (i = 0; i < this._mapping.buttons.length; i++) {
  72239. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72240. if (!buttonMeshName) {
  72241. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72242. continue;
  72243. }
  72244. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72245. if (!buttonMesh) {
  72246. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72247. continue;
  72248. }
  72249. var buttonMeshInfo = {
  72250. index: i,
  72251. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72252. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72253. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72254. };
  72255. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72256. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72257. }
  72258. else {
  72259. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72260. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72261. '(VALUE: ' + !!buttonMeshInfo.value +
  72262. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72263. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72264. ')');
  72265. }
  72266. }
  72267. // Axis Meshes
  72268. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72269. var axisMeshName = this._mapping.axisMeshNames[i];
  72270. if (!axisMeshName) {
  72271. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72272. continue;
  72273. }
  72274. var axisMesh = getChildByName(rootNode, axisMeshName);
  72275. if (!axisMesh) {
  72276. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72277. continue;
  72278. }
  72279. var axisMeshInfo = {
  72280. index: i,
  72281. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72282. min: getImmediateChildByName(axisMesh, 'MIN'),
  72283. max: getImmediateChildByName(axisMesh, 'MAX')
  72284. };
  72285. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72286. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72287. }
  72288. else {
  72289. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72290. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72291. '(VALUE: ' + !!axisMeshInfo.value +
  72292. ', MIN: ' + !!axisMeshInfo.min +
  72293. ', MAX:' + !!axisMeshInfo.max +
  72294. ')');
  72295. }
  72296. }
  72297. // Pointing Ray
  72298. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72299. if (!loadedMeshInfo.pointingPoseNode) {
  72300. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72301. }
  72302. else {
  72303. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72304. }
  72305. return loadedMeshInfo;
  72306. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72307. function getChildByName(node, name) {
  72308. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72309. }
  72310. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72311. function getImmediateChildByName(node, name) {
  72312. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72313. }
  72314. };
  72315. /**
  72316. * Gets the ray of the controller in the direction the controller is pointing
  72317. * @param length the length the resulting ray should be
  72318. * @returns a ray in the direction the controller is pointing
  72319. */
  72320. WindowsMotionController.prototype.getForwardRay = function (length) {
  72321. if (length === void 0) { length = 100; }
  72322. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72323. return _super.prototype.getForwardRay.call(this, length);
  72324. }
  72325. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72326. var origin = m.getTranslation();
  72327. var forward = new BABYLON.Vector3(0, 0, -1);
  72328. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72329. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72330. return new BABYLON.Ray(origin, direction, length);
  72331. };
  72332. /**
  72333. * Disposes of the controller
  72334. */
  72335. WindowsMotionController.prototype.dispose = function () {
  72336. _super.prototype.dispose.call(this);
  72337. this.onTrackpadChangedObservable.clear();
  72338. };
  72339. /**
  72340. * The base url used to load the left and right controller models
  72341. */
  72342. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72343. /**
  72344. * The name of the left controller model file
  72345. */
  72346. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72347. /**
  72348. * The name of the right controller model file
  72349. */
  72350. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72351. /**
  72352. * The controller name prefix for this controller type
  72353. */
  72354. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72355. /**
  72356. * The controller id pattern for this controller type
  72357. */
  72358. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72359. return WindowsMotionController;
  72360. }(BABYLON.WebVRController));
  72361. BABYLON.WindowsMotionController = WindowsMotionController;
  72362. })(BABYLON || (BABYLON = {}));
  72363. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72364. var BABYLON;
  72365. (function (BABYLON) {
  72366. /**
  72367. * Gear VR Controller
  72368. */
  72369. var GearVRController = /** @class */ (function (_super) {
  72370. __extends(GearVRController, _super);
  72371. /**
  72372. * Creates a new GearVRController from a gamepad
  72373. * @param vrGamepad the gamepad that the controller should be created from
  72374. */
  72375. function GearVRController(vrGamepad) {
  72376. var _this = _super.call(this, vrGamepad) || this;
  72377. _this._buttonIndexToObservableNameMap = [
  72378. 'onTrackpadChangedObservable',
  72379. 'onTriggerStateChangedObservable' // Trigger
  72380. ];
  72381. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72382. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72383. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72384. return _this;
  72385. }
  72386. /**
  72387. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72388. * @param scene scene in which to add meshes
  72389. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72390. */
  72391. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72392. var _this = this;
  72393. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72394. _this._defaultModel = newMeshes[1];
  72395. _this.attachToMesh(_this._defaultModel);
  72396. if (meshLoaded) {
  72397. meshLoaded(_this._defaultModel);
  72398. }
  72399. });
  72400. };
  72401. /**
  72402. * Called once for each button that changed state since the last frame
  72403. * @param buttonIdx Which button index changed
  72404. * @param state New state of the button
  72405. * @param changes Which properties on the state changed since last frame
  72406. */
  72407. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72408. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72409. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72410. // Only emit events for buttons that we know how to map from index to observable
  72411. var observable = this[observableName];
  72412. if (observable) {
  72413. observable.notifyObservers(state);
  72414. }
  72415. }
  72416. };
  72417. /**
  72418. * Base Url for the controller model.
  72419. */
  72420. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72421. /**
  72422. * File name for the controller model.
  72423. */
  72424. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72425. /**
  72426. * Gamepad Id prefix used to identify this controller.
  72427. */
  72428. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72429. return GearVRController;
  72430. }(BABYLON.WebVRController));
  72431. BABYLON.GearVRController = GearVRController;
  72432. })(BABYLON || (BABYLON = {}));
  72433. //# sourceMappingURL=babylon.gearVRController.js.map
  72434. var BABYLON;
  72435. (function (BABYLON) {
  72436. /**
  72437. * Google Daydream controller
  72438. */
  72439. var DaydreamController = /** @class */ (function (_super) {
  72440. __extends(DaydreamController, _super);
  72441. /**
  72442. * Creates a new DaydreamController from a gamepad
  72443. * @param vrGamepad the gamepad that the controller should be created from
  72444. */
  72445. function DaydreamController(vrGamepad) {
  72446. var _this = _super.call(this, vrGamepad) || this;
  72447. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72448. return _this;
  72449. }
  72450. /**
  72451. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72452. * @param scene scene in which to add meshes
  72453. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72454. */
  72455. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72456. var _this = this;
  72457. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72458. _this._defaultModel = newMeshes[1];
  72459. _this.attachToMesh(_this._defaultModel);
  72460. if (meshLoaded) {
  72461. meshLoaded(_this._defaultModel);
  72462. }
  72463. });
  72464. };
  72465. /**
  72466. * Called once for each button that changed state since the last frame
  72467. * @param buttonIdx Which button index changed
  72468. * @param state New state of the button
  72469. * @param changes Which properties on the state changed since last frame
  72470. */
  72471. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72472. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72473. if (buttonIdx === 0) {
  72474. var observable = this.onTriggerStateChangedObservable;
  72475. if (observable) {
  72476. observable.notifyObservers(state);
  72477. }
  72478. }
  72479. else {
  72480. // If the app or home buttons are ever made available
  72481. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72482. }
  72483. };
  72484. /**
  72485. * Base Url for the controller model.
  72486. */
  72487. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72488. /**
  72489. * File name for the controller model.
  72490. */
  72491. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72492. /**
  72493. * Gamepad Id prefix used to identify Daydream Controller.
  72494. */
  72495. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72496. return DaydreamController;
  72497. }(BABYLON.WebVRController));
  72498. BABYLON.DaydreamController = DaydreamController;
  72499. })(BABYLON || (BABYLON = {}));
  72500. //# sourceMappingURL=babylon.daydreamController.js.map
  72501. var BABYLON;
  72502. (function (BABYLON) {
  72503. var FollowCamera = /** @class */ (function (_super) {
  72504. __extends(FollowCamera, _super);
  72505. function FollowCamera(name, position, scene, lockedTarget) {
  72506. if (lockedTarget === void 0) { lockedTarget = null; }
  72507. var _this = _super.call(this, name, position, scene) || this;
  72508. _this.radius = 12;
  72509. _this.rotationOffset = 0;
  72510. _this.heightOffset = 4;
  72511. _this.cameraAcceleration = 0.05;
  72512. _this.maxCameraSpeed = 20;
  72513. _this.lockedTarget = lockedTarget;
  72514. return _this;
  72515. }
  72516. FollowCamera.prototype.getRadians = function (degrees) {
  72517. return degrees * Math.PI / 180;
  72518. };
  72519. FollowCamera.prototype.follow = function (cameraTarget) {
  72520. if (!cameraTarget)
  72521. return;
  72522. var yRotation;
  72523. if (cameraTarget.rotationQuaternion) {
  72524. var rotMatrix = new BABYLON.Matrix();
  72525. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72526. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72527. }
  72528. else {
  72529. yRotation = cameraTarget.rotation.y;
  72530. }
  72531. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72532. var targetPosition = cameraTarget.getAbsolutePosition();
  72533. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72534. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72535. var dx = targetX - this.position.x;
  72536. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72537. var dz = (targetZ) - this.position.z;
  72538. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72539. var vy = dy * this.cameraAcceleration;
  72540. var vz = dz * this.cameraAcceleration * 2;
  72541. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72542. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72543. }
  72544. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72545. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72546. }
  72547. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72548. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72549. }
  72550. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72551. this.setTarget(targetPosition);
  72552. };
  72553. FollowCamera.prototype._checkInputs = function () {
  72554. _super.prototype._checkInputs.call(this);
  72555. if (this.lockedTarget) {
  72556. this.follow(this.lockedTarget);
  72557. }
  72558. };
  72559. FollowCamera.prototype.getClassName = function () {
  72560. return "FollowCamera";
  72561. };
  72562. __decorate([
  72563. BABYLON.serialize()
  72564. ], FollowCamera.prototype, "radius", void 0);
  72565. __decorate([
  72566. BABYLON.serialize()
  72567. ], FollowCamera.prototype, "rotationOffset", void 0);
  72568. __decorate([
  72569. BABYLON.serialize()
  72570. ], FollowCamera.prototype, "heightOffset", void 0);
  72571. __decorate([
  72572. BABYLON.serialize()
  72573. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72574. __decorate([
  72575. BABYLON.serialize()
  72576. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72577. __decorate([
  72578. BABYLON.serializeAsMeshReference("lockedTargetId")
  72579. ], FollowCamera.prototype, "lockedTarget", void 0);
  72580. return FollowCamera;
  72581. }(BABYLON.TargetCamera));
  72582. BABYLON.FollowCamera = FollowCamera;
  72583. var ArcFollowCamera = /** @class */ (function (_super) {
  72584. __extends(ArcFollowCamera, _super);
  72585. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72586. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72587. _this.alpha = alpha;
  72588. _this.beta = beta;
  72589. _this.radius = radius;
  72590. _this.target = target;
  72591. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72592. _this.follow();
  72593. return _this;
  72594. }
  72595. ArcFollowCamera.prototype.follow = function () {
  72596. if (!this.target) {
  72597. return;
  72598. }
  72599. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72600. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72601. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72602. var targetPosition = this.target.getAbsolutePosition();
  72603. this.position = targetPosition.add(this._cartesianCoordinates);
  72604. this.setTarget(targetPosition);
  72605. };
  72606. ArcFollowCamera.prototype._checkInputs = function () {
  72607. _super.prototype._checkInputs.call(this);
  72608. this.follow();
  72609. };
  72610. ArcFollowCamera.prototype.getClassName = function () {
  72611. return "ArcFollowCamera";
  72612. };
  72613. return ArcFollowCamera;
  72614. }(BABYLON.TargetCamera));
  72615. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72616. })(BABYLON || (BABYLON = {}));
  72617. //# sourceMappingURL=babylon.followCamera.js.map
  72618. var BABYLON;
  72619. (function (BABYLON) {
  72620. // We're mainly based on the logic defined into the FreeCamera code
  72621. var UniversalCamera = /** @class */ (function (_super) {
  72622. __extends(UniversalCamera, _super);
  72623. //-- end properties for backward compatibility for inputs
  72624. function UniversalCamera(name, position, scene) {
  72625. var _this = _super.call(this, name, position, scene) || this;
  72626. _this.inputs.addGamepad();
  72627. return _this;
  72628. }
  72629. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72630. //-- Begin properties for backward compatibility for inputs
  72631. get: function () {
  72632. var gamepad = this.inputs.attached["gamepad"];
  72633. if (gamepad)
  72634. return gamepad.gamepadAngularSensibility;
  72635. return 0;
  72636. },
  72637. set: function (value) {
  72638. var gamepad = this.inputs.attached["gamepad"];
  72639. if (gamepad)
  72640. gamepad.gamepadAngularSensibility = value;
  72641. },
  72642. enumerable: true,
  72643. configurable: true
  72644. });
  72645. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72646. get: function () {
  72647. var gamepad = this.inputs.attached["gamepad"];
  72648. if (gamepad)
  72649. return gamepad.gamepadMoveSensibility;
  72650. return 0;
  72651. },
  72652. set: function (value) {
  72653. var gamepad = this.inputs.attached["gamepad"];
  72654. if (gamepad)
  72655. gamepad.gamepadMoveSensibility = value;
  72656. },
  72657. enumerable: true,
  72658. configurable: true
  72659. });
  72660. UniversalCamera.prototype.getClassName = function () {
  72661. return "UniversalCamera";
  72662. };
  72663. return UniversalCamera;
  72664. }(BABYLON.TouchCamera));
  72665. BABYLON.UniversalCamera = UniversalCamera;
  72666. })(BABYLON || (BABYLON = {}));
  72667. //# sourceMappingURL=babylon.universalCamera.js.map
  72668. var BABYLON;
  72669. (function (BABYLON) {
  72670. // We're mainly based on the logic defined into the FreeCamera code
  72671. var GamepadCamera = /** @class */ (function (_super) {
  72672. __extends(GamepadCamera, _super);
  72673. //-- end properties for backward compatibility for inputs
  72674. function GamepadCamera(name, position, scene) {
  72675. return _super.call(this, name, position, scene) || this;
  72676. }
  72677. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72678. //-- Begin properties for backward compatibility for inputs
  72679. get: function () {
  72680. var gamepad = this.inputs.attached["gamepad"];
  72681. if (gamepad)
  72682. return gamepad.gamepadAngularSensibility;
  72683. return 0;
  72684. },
  72685. set: function (value) {
  72686. var gamepad = this.inputs.attached["gamepad"];
  72687. if (gamepad)
  72688. gamepad.gamepadAngularSensibility = value;
  72689. },
  72690. enumerable: true,
  72691. configurable: true
  72692. });
  72693. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72694. get: function () {
  72695. var gamepad = this.inputs.attached["gamepad"];
  72696. if (gamepad)
  72697. return gamepad.gamepadMoveSensibility;
  72698. return 0;
  72699. },
  72700. set: function (value) {
  72701. var gamepad = this.inputs.attached["gamepad"];
  72702. if (gamepad)
  72703. gamepad.gamepadMoveSensibility = value;
  72704. },
  72705. enumerable: true,
  72706. configurable: true
  72707. });
  72708. GamepadCamera.prototype.getClassName = function () {
  72709. return "GamepadCamera";
  72710. };
  72711. return GamepadCamera;
  72712. }(BABYLON.UniversalCamera));
  72713. BABYLON.GamepadCamera = GamepadCamera;
  72714. })(BABYLON || (BABYLON = {}));
  72715. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72716. var BABYLON;
  72717. (function (BABYLON) {
  72718. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72719. function PostProcessRenderPipelineManager() {
  72720. this._renderPipelines = {};
  72721. }
  72722. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72723. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72724. };
  72725. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72726. if (unique === void 0) { unique = false; }
  72727. var renderPipeline = this._renderPipelines[renderPipelineName];
  72728. if (!renderPipeline) {
  72729. return;
  72730. }
  72731. renderPipeline._attachCameras(cameras, unique);
  72732. };
  72733. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72734. var renderPipeline = this._renderPipelines[renderPipelineName];
  72735. if (!renderPipeline) {
  72736. return;
  72737. }
  72738. renderPipeline._detachCameras(cameras);
  72739. };
  72740. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72741. var renderPipeline = this._renderPipelines[renderPipelineName];
  72742. if (!renderPipeline) {
  72743. return;
  72744. }
  72745. renderPipeline._enableEffect(renderEffectName, cameras);
  72746. };
  72747. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72748. var renderPipeline = this._renderPipelines[renderPipelineName];
  72749. if (!renderPipeline) {
  72750. return;
  72751. }
  72752. renderPipeline._disableEffect(renderEffectName, cameras);
  72753. };
  72754. PostProcessRenderPipelineManager.prototype.update = function () {
  72755. for (var renderPipelineName in this._renderPipelines) {
  72756. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72757. var pipeline = this._renderPipelines[renderPipelineName];
  72758. if (!pipeline.isSupported) {
  72759. pipeline.dispose();
  72760. delete this._renderPipelines[renderPipelineName];
  72761. }
  72762. else {
  72763. pipeline._update();
  72764. }
  72765. }
  72766. }
  72767. };
  72768. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72769. for (var renderPipelineName in this._renderPipelines) {
  72770. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72771. var pipeline = this._renderPipelines[renderPipelineName];
  72772. pipeline._rebuild();
  72773. }
  72774. }
  72775. };
  72776. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72777. for (var renderPipelineName in this._renderPipelines) {
  72778. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72779. var pipeline = this._renderPipelines[renderPipelineName];
  72780. pipeline.dispose();
  72781. }
  72782. }
  72783. };
  72784. return PostProcessRenderPipelineManager;
  72785. }());
  72786. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72787. })(BABYLON || (BABYLON = {}));
  72788. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72789. var BABYLON;
  72790. (function (BABYLON) {
  72791. /**
  72792. * This represents a set of one or more post processes in Babylon.
  72793. * A post process can be used to apply a shader to a texture after it is rendered.
  72794. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72795. */
  72796. var PostProcessRenderEffect = /** @class */ (function () {
  72797. /**
  72798. * Instantiates a post process render effect.
  72799. * A post process can be used to apply a shader to a texture after it is rendered.
  72800. * @param engine The engine the effect is tied to
  72801. * @param name The name of the effect
  72802. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72803. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72804. */
  72805. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72806. this._name = name;
  72807. this._singleInstance = singleInstance || true;
  72808. this._getPostProcesses = getPostProcesses;
  72809. this._cameras = {};
  72810. this._indicesForCamera = {};
  72811. this._postProcesses = {};
  72812. }
  72813. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72814. /**
  72815. * Checks if all the post processes in the effect are supported.
  72816. */
  72817. get: function () {
  72818. for (var index in this._postProcesses) {
  72819. if (this._postProcesses.hasOwnProperty(index)) {
  72820. var pps = this._postProcesses[index];
  72821. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72822. if (!pps[ppIndex].isSupported) {
  72823. return false;
  72824. }
  72825. }
  72826. }
  72827. }
  72828. return true;
  72829. },
  72830. enumerable: true,
  72831. configurable: true
  72832. });
  72833. /**
  72834. * Updates the current state of the effect
  72835. */
  72836. PostProcessRenderEffect.prototype._update = function () {
  72837. };
  72838. /**
  72839. * Attaches the effect on cameras
  72840. * @param cameras The camera to attach to.
  72841. */
  72842. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72843. var _this = this;
  72844. var cameraKey;
  72845. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72846. if (!cams) {
  72847. return;
  72848. }
  72849. for (var i = 0; i < cams.length; i++) {
  72850. var camera = cams[i];
  72851. var cameraName = camera.name;
  72852. if (this._singleInstance) {
  72853. cameraKey = 0;
  72854. }
  72855. else {
  72856. cameraKey = cameraName;
  72857. }
  72858. if (!this._postProcesses[cameraKey]) {
  72859. var postProcess = this._getPostProcesses();
  72860. if (postProcess) {
  72861. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72862. }
  72863. }
  72864. if (!this._indicesForCamera[cameraName]) {
  72865. this._indicesForCamera[cameraName] = [];
  72866. }
  72867. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72868. var index = camera.attachPostProcess(postProcess);
  72869. _this._indicesForCamera[cameraName].push(index);
  72870. });
  72871. if (!this._cameras[cameraName]) {
  72872. this._cameras[cameraName] = camera;
  72873. }
  72874. }
  72875. };
  72876. /**
  72877. * Detatches the effect on cameras
  72878. * @param cameras The camera to detatch from.
  72879. */
  72880. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72881. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72882. if (!cams) {
  72883. return;
  72884. }
  72885. for (var i = 0; i < cams.length; i++) {
  72886. var camera = cams[i];
  72887. var cameraName = camera.name;
  72888. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72889. camera.detachPostProcess(postProcess);
  72890. });
  72891. if (this._cameras[cameraName]) {
  72892. //this._indicesForCamera.splice(index, 1);
  72893. this._cameras[cameraName] = null;
  72894. }
  72895. }
  72896. };
  72897. /**
  72898. * Enables the effect on given cameras
  72899. * @param cameras The camera to enable.
  72900. */
  72901. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72902. var _this = this;
  72903. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72904. if (!cams) {
  72905. return;
  72906. }
  72907. for (var i = 0; i < cams.length; i++) {
  72908. var camera = cams[i];
  72909. var cameraName = camera.name;
  72910. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72911. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72912. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72913. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72914. });
  72915. }
  72916. }
  72917. }
  72918. };
  72919. /**
  72920. * Disables the effect on the given cameras
  72921. * @param cameras The camera to disable.
  72922. */
  72923. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72924. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72925. if (!cams) {
  72926. return;
  72927. }
  72928. for (var i = 0; i < cams.length; i++) {
  72929. var camera = cams[i];
  72930. var cameraName = camera.name;
  72931. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72932. camera.detachPostProcess(postProcess);
  72933. });
  72934. }
  72935. };
  72936. /**
  72937. * Gets a list of the post processes contained in the effect.
  72938. * @param camera The camera to get the post processes on.
  72939. * @returns The list of the post processes in the effect.
  72940. */
  72941. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72942. if (this._singleInstance) {
  72943. return this._postProcesses[0];
  72944. }
  72945. else {
  72946. if (!camera) {
  72947. return null;
  72948. }
  72949. return this._postProcesses[camera.name];
  72950. }
  72951. };
  72952. return PostProcessRenderEffect;
  72953. }());
  72954. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. var PostProcessRenderPipeline = /** @class */ (function () {
  72960. function PostProcessRenderPipeline(engine, name) {
  72961. this.engine = engine;
  72962. this._name = name;
  72963. this._renderEffects = {};
  72964. this._renderEffectsForIsolatedPass = new Array();
  72965. this._cameras = [];
  72966. }
  72967. PostProcessRenderPipeline.prototype.getClassName = function () {
  72968. return "PostProcessRenderPipeline";
  72969. };
  72970. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72971. get: function () {
  72972. for (var renderEffectName in this._renderEffects) {
  72973. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72974. if (!this._renderEffects[renderEffectName].isSupported) {
  72975. return false;
  72976. }
  72977. }
  72978. }
  72979. return true;
  72980. },
  72981. enumerable: true,
  72982. configurable: true
  72983. });
  72984. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72985. this._renderEffects[renderEffect._name] = renderEffect;
  72986. };
  72987. // private
  72988. PostProcessRenderPipeline.prototype._rebuild = function () {
  72989. };
  72990. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72991. var renderEffects = this._renderEffects[renderEffectName];
  72992. if (!renderEffects) {
  72993. return;
  72994. }
  72995. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72996. };
  72997. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72998. var renderEffects = this._renderEffects[renderEffectName];
  72999. if (!renderEffects) {
  73000. return;
  73001. }
  73002. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73003. };
  73004. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73005. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73006. if (!cams) {
  73007. return;
  73008. }
  73009. var indicesToDelete = [];
  73010. var i;
  73011. for (i = 0; i < cams.length; i++) {
  73012. var camera = cams[i];
  73013. var cameraName = camera.name;
  73014. if (this._cameras.indexOf(camera) === -1) {
  73015. this._cameras[cameraName] = camera;
  73016. }
  73017. else if (unique) {
  73018. indicesToDelete.push(i);
  73019. }
  73020. }
  73021. for (i = 0; i < indicesToDelete.length; i++) {
  73022. cameras.splice(indicesToDelete[i], 1);
  73023. }
  73024. for (var renderEffectName in this._renderEffects) {
  73025. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73026. this._renderEffects[renderEffectName]._attachCameras(cams);
  73027. }
  73028. }
  73029. };
  73030. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73031. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73032. if (!cams) {
  73033. return;
  73034. }
  73035. for (var renderEffectName in this._renderEffects) {
  73036. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73037. this._renderEffects[renderEffectName]._detachCameras(cams);
  73038. }
  73039. }
  73040. for (var i = 0; i < cams.length; i++) {
  73041. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73042. }
  73043. };
  73044. PostProcessRenderPipeline.prototype._update = function () {
  73045. for (var renderEffectName in this._renderEffects) {
  73046. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73047. this._renderEffects[renderEffectName]._update();
  73048. }
  73049. }
  73050. for (var i = 0; i < this._cameras.length; i++) {
  73051. var cameraName = this._cameras[i].name;
  73052. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73053. this._renderEffectsForIsolatedPass[cameraName]._update();
  73054. }
  73055. }
  73056. };
  73057. PostProcessRenderPipeline.prototype._reset = function () {
  73058. this._renderEffects = {};
  73059. this._renderEffectsForIsolatedPass = new Array();
  73060. };
  73061. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73062. // 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)
  73063. var effectKeys = Object.keys(this._renderEffects);
  73064. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73065. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73066. if (postProcesses) {
  73067. postProcesses[0].samples = sampleCount;
  73068. return true;
  73069. }
  73070. }
  73071. return false;
  73072. };
  73073. PostProcessRenderPipeline.prototype.dispose = function () {
  73074. // Must be implemented by children
  73075. };
  73076. __decorate([
  73077. BABYLON.serialize()
  73078. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73079. return PostProcessRenderPipeline;
  73080. }());
  73081. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73082. })(BABYLON || (BABYLON = {}));
  73083. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73084. var BABYLON;
  73085. (function (BABYLON) {
  73086. /**
  73087. * This represents a depth renderer in Babylon.
  73088. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73089. */
  73090. var DepthRenderer = /** @class */ (function () {
  73091. /**
  73092. * Instantiates a depth renderer
  73093. * @param scene The scene the renderer belongs to
  73094. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73095. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73096. */
  73097. function DepthRenderer(scene, type, camera) {
  73098. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73099. if (camera === void 0) { camera = null; }
  73100. var _this = this;
  73101. this._scene = scene;
  73102. this._camera = camera;
  73103. var engine = scene.getEngine();
  73104. // Render target
  73105. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73106. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73107. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73108. this._depthMap.refreshRate = 1;
  73109. this._depthMap.renderParticles = false;
  73110. this._depthMap.renderList = null;
  73111. // Camera to get depth map from to support multiple concurrent cameras
  73112. this._depthMap.activeCamera = this._camera;
  73113. this._depthMap.ignoreCameraViewport = true;
  73114. this._depthMap.useCameraPostProcesses = false;
  73115. // set default depth value to 1.0 (far away)
  73116. this._depthMap.onClearObservable.add(function (engine) {
  73117. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73118. });
  73119. // Custom render function
  73120. var renderSubMesh = function (subMesh) {
  73121. var mesh = subMesh.getRenderingMesh();
  73122. var scene = _this._scene;
  73123. var engine = scene.getEngine();
  73124. var material = subMesh.getMaterial();
  73125. if (!material) {
  73126. return;
  73127. }
  73128. // Culling and reverse (right handed system)
  73129. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73130. // Managing instances
  73131. var batch = mesh._getInstancesRenderList(subMesh._id);
  73132. if (batch.mustReturn) {
  73133. return;
  73134. }
  73135. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73136. var camera = _this._camera || scene.activeCamera;
  73137. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73138. engine.enableEffect(_this._effect);
  73139. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73140. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73141. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73142. // Alpha test
  73143. if (material && material.needAlphaTesting()) {
  73144. var alphaTexture = material.getAlphaTestTexture();
  73145. if (alphaTexture) {
  73146. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73147. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73148. }
  73149. }
  73150. // Bones
  73151. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73152. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73153. }
  73154. // Draw
  73155. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73156. }
  73157. };
  73158. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73159. var index;
  73160. if (depthOnlySubMeshes.length) {
  73161. engine.setColorWrite(false);
  73162. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73163. renderSubMesh(depthOnlySubMeshes.data[index]);
  73164. }
  73165. engine.setColorWrite(true);
  73166. }
  73167. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73168. renderSubMesh(opaqueSubMeshes.data[index]);
  73169. }
  73170. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73171. renderSubMesh(alphaTestSubMeshes.data[index]);
  73172. }
  73173. };
  73174. }
  73175. /**
  73176. * Creates the depth rendering effect and checks if the effect is ready.
  73177. * @param subMesh The submesh to be used to render the depth map of
  73178. * @param useInstances If multiple world instances should be used
  73179. * @returns if the depth renderer is ready to render the depth map
  73180. */
  73181. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73182. var material = subMesh.getMaterial();
  73183. if (material.disableDepthWrite) {
  73184. return false;
  73185. }
  73186. var defines = [];
  73187. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73188. var mesh = subMesh.getMesh();
  73189. // Alpha test
  73190. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73191. defines.push("#define ALPHATEST");
  73192. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73193. attribs.push(BABYLON.VertexBuffer.UVKind);
  73194. defines.push("#define UV1");
  73195. }
  73196. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73197. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73198. defines.push("#define UV2");
  73199. }
  73200. }
  73201. // Bones
  73202. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73203. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73204. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73205. if (mesh.numBoneInfluencers > 4) {
  73206. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73207. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73208. }
  73209. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73210. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73211. }
  73212. else {
  73213. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73214. }
  73215. // Instances
  73216. if (useInstances) {
  73217. defines.push("#define INSTANCES");
  73218. attribs.push("world0");
  73219. attribs.push("world1");
  73220. attribs.push("world2");
  73221. attribs.push("world3");
  73222. }
  73223. // Get correct effect
  73224. var join = defines.join("\n");
  73225. if (this._cachedDefines !== join) {
  73226. this._cachedDefines = join;
  73227. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73228. }
  73229. return this._effect.isReady();
  73230. };
  73231. /**
  73232. * Gets the texture which the depth map will be written to.
  73233. * @returns The depth map texture
  73234. */
  73235. DepthRenderer.prototype.getDepthMap = function () {
  73236. return this._depthMap;
  73237. };
  73238. /**
  73239. * Disposes of the depth renderer.
  73240. */
  73241. DepthRenderer.prototype.dispose = function () {
  73242. this._depthMap.dispose();
  73243. };
  73244. return DepthRenderer;
  73245. }());
  73246. BABYLON.DepthRenderer = DepthRenderer;
  73247. })(BABYLON || (BABYLON = {}));
  73248. //# sourceMappingURL=babylon.depthRenderer.js.map
  73249. var BABYLON;
  73250. (function (BABYLON) {
  73251. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73252. __extends(SSAORenderingPipeline, _super);
  73253. /**
  73254. * @constructor
  73255. * @param {string} name - The rendering pipeline name
  73256. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73257. * @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 }
  73258. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73259. */
  73260. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73261. var _this = _super.call(this, scene.getEngine(), name) || this;
  73262. // Members
  73263. /**
  73264. * The PassPostProcess id in the pipeline that contains the original scene color
  73265. */
  73266. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73267. /**
  73268. * The SSAO PostProcess id in the pipeline
  73269. */
  73270. _this.SSAORenderEffect = "SSAORenderEffect";
  73271. /**
  73272. * The horizontal blur PostProcess id in the pipeline
  73273. */
  73274. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73275. /**
  73276. * The vertical blur PostProcess id in the pipeline
  73277. */
  73278. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73279. /**
  73280. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73281. */
  73282. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73283. /**
  73284. * The output strength of the SSAO post-process. Default value is 1.0.
  73285. */
  73286. _this.totalStrength = 1.0;
  73287. /**
  73288. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73289. */
  73290. _this.radius = 0.0001;
  73291. /**
  73292. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73293. * Must not be equal to fallOff and superior to fallOff.
  73294. * Default value is 0.975
  73295. */
  73296. _this.area = 0.0075;
  73297. /**
  73298. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73299. * Must not be equal to area and inferior to area.
  73300. * Default value is 0.0
  73301. */
  73302. _this.fallOff = 0.000001;
  73303. /**
  73304. * The base color of the SSAO post-process
  73305. * The final result is "base + ssao" between [0, 1]
  73306. */
  73307. _this.base = 0.5;
  73308. _this._firstUpdate = true;
  73309. _this._scene = scene;
  73310. // Set up assets
  73311. _this._createRandomTexture();
  73312. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73313. var ssaoRatio = ratio.ssaoRatio || ratio;
  73314. var combineRatio = ratio.combineRatio || ratio;
  73315. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73316. _this._createSSAOPostProcess(ssaoRatio);
  73317. _this._createBlurPostProcess(ssaoRatio);
  73318. _this._createSSAOCombinePostProcess(combineRatio);
  73319. // Set up pipeline
  73320. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73325. // Finish
  73326. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73327. if (cameras)
  73328. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73329. return _this;
  73330. }
  73331. // Public Methods
  73332. /**
  73333. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73334. */
  73335. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73336. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73337. for (var i = 0; i < this._scene.cameras.length; i++) {
  73338. var camera = this._scene.cameras[i];
  73339. this._originalColorPostProcess.dispose(camera);
  73340. this._ssaoPostProcess.dispose(camera);
  73341. this._blurHPostProcess.dispose(camera);
  73342. this._blurVPostProcess.dispose(camera);
  73343. this._ssaoCombinePostProcess.dispose(camera);
  73344. }
  73345. this._randomTexture.dispose();
  73346. if (disableDepthRender)
  73347. this._scene.disableDepthRenderer();
  73348. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73349. _super.prototype.dispose.call(this);
  73350. };
  73351. // Private Methods
  73352. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73353. var _this = this;
  73354. var size = 16;
  73355. 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);
  73356. 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);
  73357. this._blurHPostProcess.onActivateObservable.add(function () {
  73358. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73359. _this._blurHPostProcess.kernel = size * dw;
  73360. });
  73361. this._blurVPostProcess.onActivateObservable.add(function () {
  73362. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73363. _this._blurVPostProcess.kernel = size * dw;
  73364. });
  73365. };
  73366. SSAORenderingPipeline.prototype._rebuild = function () {
  73367. this._firstUpdate = true;
  73368. _super.prototype._rebuild.call(this);
  73369. };
  73370. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73371. var _this = this;
  73372. var numSamples = 16;
  73373. var sampleSphere = [
  73374. 0.5381, 0.1856, -0.4319,
  73375. 0.1379, 0.2486, 0.4430,
  73376. 0.3371, 0.5679, -0.0057,
  73377. -0.6999, -0.0451, -0.0019,
  73378. 0.0689, -0.1598, -0.8547,
  73379. 0.0560, 0.0069, -0.1843,
  73380. -0.0146, 0.1402, 0.0762,
  73381. 0.0100, -0.1924, -0.0344,
  73382. -0.3577, -0.5301, -0.4358,
  73383. -0.3169, 0.1063, 0.0158,
  73384. 0.0103, -0.5869, 0.0046,
  73385. -0.0897, -0.4940, 0.3287,
  73386. 0.7119, -0.0154, -0.0918,
  73387. -0.0533, 0.0596, -0.5411,
  73388. 0.0352, -0.0631, 0.5460,
  73389. -0.4776, 0.2847, -0.0271
  73390. ];
  73391. var samplesFactor = 1.0 / numSamples;
  73392. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73393. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73394. "area", "fallOff", "base", "range", "viewport"
  73395. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73396. this._ssaoPostProcess.onApply = function (effect) {
  73397. if (_this._firstUpdate) {
  73398. effect.setArray3("sampleSphere", sampleSphere);
  73399. effect.setFloat("samplesFactor", samplesFactor);
  73400. effect.setFloat("randTextureTiles", 4.0);
  73401. }
  73402. effect.setFloat("totalStrength", _this.totalStrength);
  73403. effect.setFloat("radius", _this.radius);
  73404. effect.setFloat("area", _this.area);
  73405. effect.setFloat("fallOff", _this.fallOff);
  73406. effect.setFloat("base", _this.base);
  73407. effect.setTexture("textureSampler", _this._depthTexture);
  73408. effect.setTexture("randomSampler", _this._randomTexture);
  73409. };
  73410. };
  73411. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73412. var _this = this;
  73413. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73414. this._ssaoCombinePostProcess.onApply = function (effect) {
  73415. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73416. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73417. };
  73418. };
  73419. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73420. var size = 512;
  73421. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73422. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73423. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73424. var context = this._randomTexture.getContext();
  73425. var rand = function (min, max) {
  73426. return Math.random() * (max - min) + min;
  73427. };
  73428. var randVector = BABYLON.Vector3.Zero();
  73429. for (var x = 0; x < size; x++) {
  73430. for (var y = 0; y < size; y++) {
  73431. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73432. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73433. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73434. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73435. context.fillRect(x, y, 1, 1);
  73436. }
  73437. }
  73438. this._randomTexture.update(false);
  73439. };
  73440. __decorate([
  73441. BABYLON.serialize()
  73442. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73443. __decorate([
  73444. BABYLON.serialize()
  73445. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73446. __decorate([
  73447. BABYLON.serialize()
  73448. ], SSAORenderingPipeline.prototype, "area", void 0);
  73449. __decorate([
  73450. BABYLON.serialize()
  73451. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73452. __decorate([
  73453. BABYLON.serialize()
  73454. ], SSAORenderingPipeline.prototype, "base", void 0);
  73455. return SSAORenderingPipeline;
  73456. }(BABYLON.PostProcessRenderPipeline));
  73457. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73458. })(BABYLON || (BABYLON = {}));
  73459. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73460. var BABYLON;
  73461. (function (BABYLON) {
  73462. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73463. __extends(SSAO2RenderingPipeline, _super);
  73464. /**
  73465. * @constructor
  73466. * @param {string} name - The rendering pipeline name
  73467. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73468. * @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 }
  73469. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73470. */
  73471. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73472. var _this = _super.call(this, scene.getEngine(), name) || this;
  73473. // Members
  73474. /**
  73475. * The PassPostProcess id in the pipeline that contains the original scene color
  73476. */
  73477. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73478. /**
  73479. * The SSAO PostProcess id in the pipeline
  73480. */
  73481. _this.SSAORenderEffect = "SSAORenderEffect";
  73482. /**
  73483. * The horizontal blur PostProcess id in the pipeline
  73484. */
  73485. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73486. /**
  73487. * The vertical blur PostProcess id in the pipeline
  73488. */
  73489. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73490. /**
  73491. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73492. */
  73493. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73494. /**
  73495. * The output strength of the SSAO post-process. Default value is 1.0.
  73496. */
  73497. _this.totalStrength = 1.0;
  73498. /**
  73499. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73500. */
  73501. _this.maxZ = 100.0;
  73502. /**
  73503. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73504. */
  73505. _this.minZAspect = 0.2;
  73506. /**
  73507. * Number of samples used for the SSAO calculations. Default value is 8
  73508. */
  73509. _this._samples = 8;
  73510. /**
  73511. * Are we using bilateral blur ?
  73512. */
  73513. _this._expensiveBlur = true;
  73514. /**
  73515. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73516. */
  73517. _this.radius = 2.0;
  73518. /**
  73519. * The base color of the SSAO post-process
  73520. * The final result is "base + ssao" between [0, 1]
  73521. */
  73522. _this.base = 0.1;
  73523. _this._firstUpdate = true;
  73524. _this._scene = scene;
  73525. _this._ratio = ratio;
  73526. if (!_this.isSupported) {
  73527. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73528. return _this;
  73529. }
  73530. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73531. var blurRatio = _this._ratio.blurRatio || ratio;
  73532. // Set up assets
  73533. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73534. _this._createRandomTexture();
  73535. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73536. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73537. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73538. _this._createSSAOPostProcess(1.0);
  73539. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73540. _this._createSSAOCombinePostProcess(blurRatio);
  73541. // Set up pipeline
  73542. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73543. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73544. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73545. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73546. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73547. // Finish
  73548. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73549. if (cameras)
  73550. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73551. return _this;
  73552. }
  73553. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73554. get: function () {
  73555. return this._samples;
  73556. },
  73557. set: function (n) {
  73558. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73559. this._samples = n;
  73560. this._sampleSphere = this._generateHemisphere();
  73561. this._firstUpdate = true;
  73562. },
  73563. enumerable: true,
  73564. configurable: true
  73565. });
  73566. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73567. get: function () {
  73568. return this._expensiveBlur;
  73569. },
  73570. set: function (b) {
  73571. 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"]);
  73572. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73573. this._expensiveBlur = b;
  73574. this._firstUpdate = true;
  73575. },
  73576. enumerable: true,
  73577. configurable: true
  73578. });
  73579. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73580. /**
  73581. * Support test.
  73582. */
  73583. get: function () {
  73584. var engine = BABYLON.Engine.LastCreatedEngine;
  73585. if (!engine) {
  73586. return false;
  73587. }
  73588. return engine.getCaps().drawBuffersExtension;
  73589. },
  73590. enumerable: true,
  73591. configurable: true
  73592. });
  73593. // Public Methods
  73594. /**
  73595. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73596. */
  73597. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73598. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73599. for (var i = 0; i < this._scene.cameras.length; i++) {
  73600. var camera = this._scene.cameras[i];
  73601. this._originalColorPostProcess.dispose(camera);
  73602. this._ssaoPostProcess.dispose(camera);
  73603. this._blurHPostProcess.dispose(camera);
  73604. this._blurVPostProcess.dispose(camera);
  73605. this._ssaoCombinePostProcess.dispose(camera);
  73606. }
  73607. this._randomTexture.dispose();
  73608. if (disableGeometryBufferRenderer)
  73609. this._scene.disableGeometryBufferRenderer();
  73610. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73611. _super.prototype.dispose.call(this);
  73612. };
  73613. // Private Methods
  73614. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73615. var _this = this;
  73616. this._samplerOffsets = [];
  73617. var expensive = this.expensiveBlur;
  73618. for (var i = -8; i < 8; i++) {
  73619. this._samplerOffsets.push(i * 2 + 0.5);
  73620. }
  73621. 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");
  73622. this._blurHPostProcess.onApply = function (effect) {
  73623. if (!_this._scene.activeCamera) {
  73624. return;
  73625. }
  73626. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73627. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73628. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73629. effect.setFloat("radius", _this.radius);
  73630. effect.setTexture("depthSampler", _this._depthTexture);
  73631. if (_this._firstUpdate) {
  73632. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73633. }
  73634. };
  73635. 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");
  73636. this._blurVPostProcess.onApply = function (effect) {
  73637. if (!_this._scene.activeCamera) {
  73638. return;
  73639. }
  73640. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73641. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73642. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73643. effect.setFloat("radius", _this.radius);
  73644. effect.setTexture("depthSampler", _this._depthTexture);
  73645. if (_this._firstUpdate) {
  73646. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73647. _this._firstUpdate = false;
  73648. }
  73649. };
  73650. };
  73651. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73652. this._firstUpdate = true;
  73653. _super.prototype._rebuild.call(this);
  73654. };
  73655. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73656. var numSamples = this.samples;
  73657. var result = [];
  73658. var vector, scale;
  73659. var rand = function (min, max) {
  73660. return Math.random() * (max - min) + min;
  73661. };
  73662. var i = 0;
  73663. while (i < numSamples) {
  73664. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73665. vector.normalize();
  73666. scale = i / numSamples;
  73667. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73668. vector.scaleInPlace(scale);
  73669. result.push(vector.x, vector.y, vector.z);
  73670. i++;
  73671. }
  73672. return result;
  73673. };
  73674. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73675. var _this = this;
  73676. var numSamples = this.samples;
  73677. this._sampleSphere = this._generateHemisphere();
  73678. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73679. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73680. "base", "range", "projection", "near", "far", "texelSize",
  73681. "xViewport", "yViewport", "maxZ", "minZAspect"
  73682. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73683. this._ssaoPostProcess.onApply = function (effect) {
  73684. if (_this._firstUpdate) {
  73685. effect.setArray3("sampleSphere", _this._sampleSphere);
  73686. effect.setFloat("randTextureTiles", 4.0);
  73687. }
  73688. if (!_this._scene.activeCamera) {
  73689. return;
  73690. }
  73691. effect.setFloat("samplesFactor", 1 / _this.samples);
  73692. effect.setFloat("totalStrength", _this.totalStrength);
  73693. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73694. effect.setFloat("radius", _this.radius);
  73695. effect.setFloat("maxZ", _this.maxZ);
  73696. effect.setFloat("minZAspect", _this.minZAspect);
  73697. effect.setFloat("base", _this.base);
  73698. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73699. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73700. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73701. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73702. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73703. effect.setTexture("textureSampler", _this._depthTexture);
  73704. effect.setTexture("normalSampler", _this._normalTexture);
  73705. effect.setTexture("randomSampler", _this._randomTexture);
  73706. };
  73707. };
  73708. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73709. var _this = this;
  73710. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73711. this._ssaoCombinePostProcess.onApply = function (effect) {
  73712. var viewport = _this._scene.activeCamera.viewport;
  73713. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  73714. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73715. };
  73716. };
  73717. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73718. var size = 512;
  73719. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73720. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73721. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73722. var context = this._randomTexture.getContext();
  73723. var rand = function (min, max) {
  73724. return Math.random() * (max - min) + min;
  73725. };
  73726. var randVector = BABYLON.Vector3.Zero();
  73727. for (var x = 0; x < size; x++) {
  73728. for (var y = 0; y < size; y++) {
  73729. randVector.x = rand(0.0, 1.0);
  73730. randVector.y = rand(0.0, 1.0);
  73731. randVector.z = 0.0;
  73732. randVector.normalize();
  73733. randVector.scaleInPlace(255);
  73734. randVector.x = Math.floor(randVector.x);
  73735. randVector.y = Math.floor(randVector.y);
  73736. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73737. context.fillRect(x, y, 1, 1);
  73738. }
  73739. }
  73740. this._randomTexture.update(false);
  73741. };
  73742. /**
  73743. * Serialize the rendering pipeline (Used when exporting)
  73744. * @returns the serialized object
  73745. */
  73746. SSAO2RenderingPipeline.prototype.serialize = function () {
  73747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73748. serializationObject.customType = "SSAO2RenderingPipeline";
  73749. return serializationObject;
  73750. };
  73751. /**
  73752. * Parse the serialized pipeline
  73753. * @param source Source pipeline.
  73754. * @param scene The scene to load the pipeline to.
  73755. * @param rootUrl The URL of the serialized pipeline.
  73756. * @returns An instantiated pipeline from the serialized object.
  73757. */
  73758. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73759. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73760. };
  73761. __decorate([
  73762. BABYLON.serialize()
  73763. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73764. __decorate([
  73765. BABYLON.serialize()
  73766. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73767. __decorate([
  73768. BABYLON.serialize()
  73769. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73770. __decorate([
  73771. BABYLON.serialize("samples")
  73772. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73773. __decorate([
  73774. BABYLON.serialize()
  73775. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73776. __decorate([
  73777. BABYLON.serialize("expensiveBlur")
  73778. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73779. __decorate([
  73780. BABYLON.serialize()
  73781. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73782. __decorate([
  73783. BABYLON.serialize()
  73784. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73785. return SSAO2RenderingPipeline;
  73786. }(BABYLON.PostProcessRenderPipeline));
  73787. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73788. })(BABYLON || (BABYLON = {}));
  73789. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73790. // BABYLON.JS Chromatic Aberration GLSL Shader
  73791. // Author: Olivier Guyot
  73792. // Separates very slightly R, G and B colors on the edges of the screen
  73793. // Inspired by Francois Tarlier & Martins Upitis
  73794. var BABYLON;
  73795. (function (BABYLON) {
  73796. var LensRenderingPipeline = /** @class */ (function (_super) {
  73797. __extends(LensRenderingPipeline, _super);
  73798. /**
  73799. * @constructor
  73800. *
  73801. * Effect parameters are as follow:
  73802. * {
  73803. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73804. * edge_blur: number; // from 0 to x (1 for realism)
  73805. * distortion: number; // from 0 to x (1 for realism)
  73806. * grain_amount: number; // from 0 to 1
  73807. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73808. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73809. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73810. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73811. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73812. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73813. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73814. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73815. * }
  73816. * Note: if an effect parameter is unset, effect is disabled
  73817. *
  73818. * @param {string} name - The rendering pipeline name
  73819. * @param {object} parameters - An object containing all parameters (see above)
  73820. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73821. * @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)
  73822. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73823. */
  73824. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73825. if (ratio === void 0) { ratio = 1.0; }
  73826. var _this = _super.call(this, scene.getEngine(), name) || this;
  73827. // Lens effects can be of the following:
  73828. // - chromatic aberration (slight shift of RGB colors)
  73829. // - blur on the edge of the lens
  73830. // - lens distortion
  73831. // - depth-of-field blur & highlights enhancing
  73832. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73833. // - grain effect (noise or custom texture)
  73834. // Two additional texture samplers are needed:
  73835. // - depth map (for depth-of-field)
  73836. // - grain texture
  73837. /**
  73838. * The chromatic aberration PostProcess id in the pipeline
  73839. */
  73840. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73841. /**
  73842. * The highlights enhancing PostProcess id in the pipeline
  73843. */
  73844. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73845. /**
  73846. * The depth-of-field PostProcess id in the pipeline
  73847. */
  73848. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73849. _this._scene = scene;
  73850. // Fetch texture samplers
  73851. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73852. if (parameters.grain_texture) {
  73853. _this._grainTexture = parameters.grain_texture;
  73854. }
  73855. else {
  73856. _this._createGrainTexture();
  73857. }
  73858. // save parameters
  73859. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73860. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73861. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73862. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73863. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73864. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73865. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73866. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73867. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73868. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73869. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73870. // Create effects
  73871. _this._createChromaticAberrationPostProcess(ratio);
  73872. _this._createHighlightsPostProcess(ratio);
  73873. _this._createDepthOfFieldPostProcess(ratio / 4);
  73874. // Set up pipeline
  73875. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73876. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73877. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73878. if (_this._highlightsGain === -1) {
  73879. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73880. }
  73881. // Finish
  73882. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73883. if (cameras) {
  73884. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73885. }
  73886. return _this;
  73887. }
  73888. // public methods (self explanatory)
  73889. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73890. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73891. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73892. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73893. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73894. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73895. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73896. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73897. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73898. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73899. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73900. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73901. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73902. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73903. };
  73904. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73905. this._highlightsPostProcess.updateEffect();
  73906. };
  73907. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73908. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73909. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73910. this._highlightsGain = amount;
  73911. };
  73912. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73913. if (this._highlightsGain === -1) {
  73914. this._highlightsGain = 1.0;
  73915. }
  73916. this._highlightsThreshold = amount;
  73917. };
  73918. LensRenderingPipeline.prototype.disableHighlights = function () {
  73919. this._highlightsGain = -1;
  73920. };
  73921. /**
  73922. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73923. */
  73924. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73925. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73926. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73927. this._chromaticAberrationPostProcess = null;
  73928. this._highlightsPostProcess = null;
  73929. this._depthOfFieldPostProcess = null;
  73930. this._grainTexture.dispose();
  73931. if (disableDepthRender)
  73932. this._scene.disableDepthRenderer();
  73933. };
  73934. // colors shifting and distortion
  73935. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73936. var _this = this;
  73937. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73938. [], // samplers
  73939. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73940. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73941. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73942. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73943. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73944. effect.setFloat('radialIntensity', 1);
  73945. effect.setFloat2('direction', 17, 17);
  73946. effect.setFloat2('centerPosition', 0.5, 0.5);
  73947. };
  73948. };
  73949. // highlights enhancing
  73950. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73951. var _this = this;
  73952. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73953. [], // samplers
  73954. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73955. this._highlightsPostProcess.onApply = function (effect) {
  73956. effect.setFloat('gain', _this._highlightsGain);
  73957. effect.setFloat('threshold', _this._highlightsThreshold);
  73958. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73959. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73960. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73961. };
  73962. };
  73963. // colors shifting and distortion
  73964. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73965. var _this = this;
  73966. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73967. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73968. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73969. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73970. this._depthOfFieldPostProcess.onApply = function (effect) {
  73971. effect.setTexture("depthSampler", _this._depthTexture);
  73972. effect.setTexture("grainSampler", _this._grainTexture);
  73973. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73974. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73975. effect.setFloat('grain_amount', _this._grainAmount);
  73976. effect.setBool('blur_noise', _this._blurNoise);
  73977. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73978. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73979. effect.setFloat('distortion', _this._distortion);
  73980. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73981. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73982. effect.setFloat('aperture', _this._dofAperture);
  73983. effect.setFloat('darken', _this._dofDarken);
  73984. effect.setFloat('edge_blur', _this._edgeBlur);
  73985. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73986. if (_this._scene.activeCamera) {
  73987. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73988. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73989. }
  73990. };
  73991. };
  73992. // creates a black and white random noise texture, 512x512
  73993. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73994. var size = 512;
  73995. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73996. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73997. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73998. var context = this._grainTexture.getContext();
  73999. var rand = function (min, max) {
  74000. return Math.random() * (max - min) + min;
  74001. };
  74002. var value;
  74003. for (var x = 0; x < size; x++) {
  74004. for (var y = 0; y < size; y++) {
  74005. value = Math.floor(rand(0.42, 0.58) * 255);
  74006. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74007. context.fillRect(x, y, 1, 1);
  74008. }
  74009. }
  74010. this._grainTexture.update(false);
  74011. };
  74012. return LensRenderingPipeline;
  74013. }(BABYLON.PostProcessRenderPipeline));
  74014. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74015. })(BABYLON || (BABYLON = {}));
  74016. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74017. var BABYLON;
  74018. (function (BABYLON) {
  74019. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74020. __extends(StandardRenderingPipeline, _super);
  74021. /**
  74022. * @constructor
  74023. * @param {string} name - The rendering pipeline name
  74024. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74025. * @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)
  74026. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74027. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74028. */
  74029. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74030. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74031. var _this = _super.call(this, scene.getEngine(), name) || this;
  74032. _this.downSampleX4PostProcess = null;
  74033. _this.brightPassPostProcess = null;
  74034. _this.blurHPostProcesses = [];
  74035. _this.blurVPostProcesses = [];
  74036. _this.textureAdderPostProcess = null;
  74037. _this.volumetricLightPostProcess = null;
  74038. _this.volumetricLightSmoothXPostProcess = null;
  74039. _this.volumetricLightSmoothYPostProcess = null;
  74040. _this.volumetricLightMergePostProces = null;
  74041. _this.volumetricLightFinalPostProcess = null;
  74042. _this.luminancePostProcess = null;
  74043. _this.luminanceDownSamplePostProcesses = [];
  74044. _this.hdrPostProcess = null;
  74045. _this.textureAdderFinalPostProcess = null;
  74046. _this.lensFlareFinalPostProcess = null;
  74047. _this.hdrFinalPostProcess = null;
  74048. _this.lensFlarePostProcess = null;
  74049. _this.lensFlareComposePostProcess = null;
  74050. _this.motionBlurPostProcess = null;
  74051. _this.depthOfFieldPostProcess = null;
  74052. // Values
  74053. _this.brightThreshold = 1.0;
  74054. _this.blurWidth = 512.0;
  74055. _this.horizontalBlur = false;
  74056. _this.exposure = 1.0;
  74057. _this.lensTexture = null;
  74058. _this.volumetricLightCoefficient = 0.2;
  74059. _this.volumetricLightPower = 4.0;
  74060. _this.volumetricLightBlurScale = 64.0;
  74061. _this.sourceLight = null;
  74062. _this.hdrMinimumLuminance = 1.0;
  74063. _this.hdrDecreaseRate = 0.5;
  74064. _this.hdrIncreaseRate = 0.5;
  74065. _this.lensColorTexture = null;
  74066. _this.lensFlareStrength = 20.0;
  74067. _this.lensFlareGhostDispersal = 1.4;
  74068. _this.lensFlareHaloWidth = 0.7;
  74069. _this.lensFlareDistortionStrength = 16.0;
  74070. _this.lensStarTexture = null;
  74071. _this.lensFlareDirtTexture = null;
  74072. _this.depthOfFieldDistance = 10.0;
  74073. _this.depthOfFieldBlurWidth = 64.0;
  74074. _this.motionStrength = 1.0;
  74075. // IAnimatable
  74076. _this.animations = [];
  74077. _this._currentDepthOfFieldSource = null;
  74078. _this._hdrCurrentLuminance = 1.0;
  74079. // Getters and setters
  74080. _this._bloomEnabled = true;
  74081. _this._depthOfFieldEnabled = false;
  74082. _this._vlsEnabled = false;
  74083. _this._lensFlareEnabled = false;
  74084. _this._hdrEnabled = false;
  74085. _this._motionBlurEnabled = false;
  74086. _this._motionBlurSamples = 64.0;
  74087. _this._volumetricLightStepsCount = 50.0;
  74088. _this._cameras = cameras || [];
  74089. // Initialize
  74090. _this._scene = scene;
  74091. _this._basePostProcess = originalPostProcess;
  74092. _this._ratio = ratio;
  74093. // Misc
  74094. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74095. // Finish
  74096. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74097. _this._buildPipeline();
  74098. return _this;
  74099. }
  74100. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74101. get: function () {
  74102. return this._bloomEnabled;
  74103. },
  74104. set: function (enabled) {
  74105. if (this._bloomEnabled === enabled) {
  74106. return;
  74107. }
  74108. this._bloomEnabled = enabled;
  74109. this._buildPipeline();
  74110. },
  74111. enumerable: true,
  74112. configurable: true
  74113. });
  74114. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74115. get: function () {
  74116. return this._depthOfFieldEnabled;
  74117. },
  74118. set: function (enabled) {
  74119. if (this._depthOfFieldEnabled === enabled) {
  74120. return;
  74121. }
  74122. this._depthOfFieldEnabled = enabled;
  74123. this._buildPipeline();
  74124. },
  74125. enumerable: true,
  74126. configurable: true
  74127. });
  74128. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74129. get: function () {
  74130. return this._lensFlareEnabled;
  74131. },
  74132. set: function (enabled) {
  74133. if (this._lensFlareEnabled === enabled) {
  74134. return;
  74135. }
  74136. this._lensFlareEnabled = enabled;
  74137. this._buildPipeline();
  74138. },
  74139. enumerable: true,
  74140. configurable: true
  74141. });
  74142. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74143. get: function () {
  74144. return this._hdrEnabled;
  74145. },
  74146. set: function (enabled) {
  74147. if (this._hdrEnabled === enabled) {
  74148. return;
  74149. }
  74150. this._hdrEnabled = enabled;
  74151. this._buildPipeline();
  74152. },
  74153. enumerable: true,
  74154. configurable: true
  74155. });
  74156. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74157. get: function () {
  74158. return this._vlsEnabled;
  74159. },
  74160. set: function (enabled) {
  74161. if (this._vlsEnabled === enabled) {
  74162. return;
  74163. }
  74164. if (enabled) {
  74165. var geometry = this._scene.enableGeometryBufferRenderer();
  74166. if (!geometry) {
  74167. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74168. return;
  74169. }
  74170. }
  74171. this._vlsEnabled = enabled;
  74172. this._buildPipeline();
  74173. },
  74174. enumerable: true,
  74175. configurable: true
  74176. });
  74177. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74178. get: function () {
  74179. return this._motionBlurEnabled;
  74180. },
  74181. set: function (enabled) {
  74182. if (this._motionBlurEnabled === enabled) {
  74183. return;
  74184. }
  74185. this._motionBlurEnabled = enabled;
  74186. this._buildPipeline();
  74187. },
  74188. enumerable: true,
  74189. configurable: true
  74190. });
  74191. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74192. get: function () {
  74193. return this._volumetricLightStepsCount;
  74194. },
  74195. set: function (count) {
  74196. if (this.volumetricLightPostProcess) {
  74197. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74198. }
  74199. this._volumetricLightStepsCount = count;
  74200. },
  74201. enumerable: true,
  74202. configurable: true
  74203. });
  74204. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74205. get: function () {
  74206. return this._motionBlurSamples;
  74207. },
  74208. set: function (samples) {
  74209. if (this.motionBlurPostProcess) {
  74210. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74211. }
  74212. this._motionBlurSamples = samples;
  74213. },
  74214. enumerable: true,
  74215. configurable: true
  74216. });
  74217. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74218. var _this = this;
  74219. var ratio = this._ratio;
  74220. var scene = this._scene;
  74221. this._disposePostProcesses();
  74222. this._reset();
  74223. // Create pass post-process
  74224. if (!this._basePostProcess) {
  74225. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74226. this.originalPostProcess.onApply = function (effect) {
  74227. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74228. };
  74229. }
  74230. else {
  74231. this.originalPostProcess = this._basePostProcess;
  74232. }
  74233. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74234. this._currentDepthOfFieldSource = this.originalPostProcess;
  74235. if (this._bloomEnabled) {
  74236. // Create down sample X4 post-process
  74237. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74238. // Create bright pass post-process
  74239. this._createBrightPassPostProcess(scene, ratio / 2);
  74240. // Create gaussian blur post-processes (down sampling blurs)
  74241. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74242. // Create texture adder post-process
  74243. this._createTextureAdderPostProcess(scene, ratio);
  74244. // Create depth-of-field source post-process
  74245. 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);
  74246. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74247. }
  74248. if (this._vlsEnabled) {
  74249. // Create volumetric light
  74250. this._createVolumetricLightPostProcess(scene, ratio);
  74251. // Create volumetric light final post-process
  74252. 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);
  74253. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74254. }
  74255. if (this._lensFlareEnabled) {
  74256. // Create lens flare post-process
  74257. this._createLensFlarePostProcess(scene, ratio);
  74258. // Create depth-of-field source post-process post lens-flare and disable it now
  74259. 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);
  74260. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74261. }
  74262. if (this._hdrEnabled) {
  74263. // Create luminance
  74264. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74265. // Create HDR
  74266. this._createHdrPostProcess(scene, ratio);
  74267. // Create depth-of-field source post-process post hdr and disable it now
  74268. 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);
  74269. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74270. }
  74271. if (this._depthOfFieldEnabled) {
  74272. // Create gaussian blur used by depth-of-field
  74273. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74274. // Create depth-of-field post-process
  74275. this._createDepthOfFieldPostProcess(scene, ratio);
  74276. }
  74277. if (this._motionBlurEnabled) {
  74278. // Create motion blur post-process
  74279. this._createMotionBlurPostProcess(scene, ratio);
  74280. }
  74281. if (this._cameras !== null) {
  74282. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74283. }
  74284. };
  74285. // Down Sample X4 Post-Processs
  74286. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74287. var _this = this;
  74288. var downSampleX4Offsets = new Array(32);
  74289. 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);
  74290. this.downSampleX4PostProcess.onApply = function (effect) {
  74291. var id = 0;
  74292. var width = _this.downSampleX4PostProcess.width;
  74293. var height = _this.downSampleX4PostProcess.height;
  74294. for (var i = -2; i < 2; i++) {
  74295. for (var j = -2; j < 2; j++) {
  74296. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74297. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74298. id += 2;
  74299. }
  74300. }
  74301. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74302. };
  74303. // Add to pipeline
  74304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74305. };
  74306. // Brightpass Post-Process
  74307. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74308. var _this = this;
  74309. var brightOffsets = new Array(8);
  74310. 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);
  74311. this.brightPassPostProcess.onApply = function (effect) {
  74312. var sU = (1.0 / _this.brightPassPostProcess.width);
  74313. var sV = (1.0 / _this.brightPassPostProcess.height);
  74314. brightOffsets[0] = -0.5 * sU;
  74315. brightOffsets[1] = 0.5 * sV;
  74316. brightOffsets[2] = 0.5 * sU;
  74317. brightOffsets[3] = 0.5 * sV;
  74318. brightOffsets[4] = -0.5 * sU;
  74319. brightOffsets[5] = -0.5 * sV;
  74320. brightOffsets[6] = 0.5 * sU;
  74321. brightOffsets[7] = -0.5 * sV;
  74322. effect.setArray2("dsOffsets", brightOffsets);
  74323. effect.setFloat("brightThreshold", _this.brightThreshold);
  74324. };
  74325. // Add to pipeline
  74326. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74327. };
  74328. // Create blur H&V post-processes
  74329. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74330. var _this = this;
  74331. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74332. var engine = scene.getEngine();
  74333. 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);
  74334. 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);
  74335. blurX.onActivateObservable.add(function () {
  74336. var dw = blurX.width / engine.getRenderWidth();
  74337. blurX.kernel = _this[blurWidthKey] * dw;
  74338. });
  74339. blurY.onActivateObservable.add(function () {
  74340. var dw = blurY.height / engine.getRenderHeight();
  74341. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74342. });
  74343. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74344. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74345. this.blurHPostProcesses.push(blurX);
  74346. this.blurVPostProcesses.push(blurY);
  74347. };
  74348. // Create texture adder post-process
  74349. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74350. var _this = this;
  74351. 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);
  74352. this.textureAdderPostProcess.onApply = function (effect) {
  74353. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74354. effect.setTexture("lensSampler", _this.lensTexture);
  74355. effect.setFloat("exposure", _this.exposure);
  74356. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74357. };
  74358. // Add to pipeline
  74359. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74360. };
  74361. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74362. var _this = this;
  74363. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74364. geometryRenderer.enablePosition = true;
  74365. var geometry = geometryRenderer.getGBuffer();
  74366. // Base post-process
  74367. 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));
  74368. var depthValues = BABYLON.Vector2.Zero();
  74369. this.volumetricLightPostProcess.onApply = function (effect) {
  74370. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74371. var generator = _this.sourceLight.getShadowGenerator();
  74372. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74373. effect.setTexture("positionSampler", geometry.textures[2]);
  74374. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74375. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74376. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74377. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74378. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74379. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74380. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74381. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74382. effect.setVector2("depthValues", depthValues);
  74383. }
  74384. };
  74385. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74386. // Smooth
  74387. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74388. // Merge
  74389. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74390. this.volumetricLightMergePostProces.onApply = function (effect) {
  74391. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74392. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74393. };
  74394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74395. };
  74396. // Create luminance
  74397. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74398. var _this = this;
  74399. // Create luminance
  74400. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74401. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74402. var offsets = [];
  74403. this.luminancePostProcess.onApply = function (effect) {
  74404. var sU = (1.0 / _this.luminancePostProcess.width);
  74405. var sV = (1.0 / _this.luminancePostProcess.height);
  74406. offsets[0] = -0.5 * sU;
  74407. offsets[1] = 0.5 * sV;
  74408. offsets[2] = 0.5 * sU;
  74409. offsets[3] = 0.5 * sV;
  74410. offsets[4] = -0.5 * sU;
  74411. offsets[5] = -0.5 * sV;
  74412. offsets[6] = 0.5 * sU;
  74413. offsets[7] = -0.5 * sV;
  74414. effect.setArray2("lumOffsets", offsets);
  74415. };
  74416. // Add to pipeline
  74417. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74418. // Create down sample luminance
  74419. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74420. var size = Math.pow(3, i);
  74421. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74422. if (i === 0) {
  74423. defines += "#define FINAL_DOWN_SAMPLER";
  74424. }
  74425. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74426. this.luminanceDownSamplePostProcesses.push(postProcess);
  74427. }
  74428. // Create callbacks and add effects
  74429. var lastLuminance = this.luminancePostProcess;
  74430. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74431. var downSampleOffsets = new Array(18);
  74432. pp.onApply = function (effect) {
  74433. if (!lastLuminance) {
  74434. return;
  74435. }
  74436. var id = 0;
  74437. for (var x = -1; x < 2; x++) {
  74438. for (var y = -1; y < 2; y++) {
  74439. downSampleOffsets[id] = x / lastLuminance.width;
  74440. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74441. id += 2;
  74442. }
  74443. }
  74444. effect.setArray2("dsOffsets", downSampleOffsets);
  74445. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74446. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74447. lastLuminance = _this.luminancePostProcess;
  74448. }
  74449. else {
  74450. lastLuminance = pp;
  74451. }
  74452. };
  74453. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74454. pp.onAfterRender = function (effect) {
  74455. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74456. 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);
  74457. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74458. };
  74459. }
  74460. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74461. });
  74462. };
  74463. // Create HDR post-process
  74464. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74465. var _this = this;
  74466. 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);
  74467. var outputLiminance = 1;
  74468. var time = 0;
  74469. var lastTime = 0;
  74470. this.hdrPostProcess.onApply = function (effect) {
  74471. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74472. time += scene.getEngine().getDeltaTime();
  74473. if (outputLiminance < 0) {
  74474. outputLiminance = _this._hdrCurrentLuminance;
  74475. }
  74476. else {
  74477. var dt = (lastTime - time) / 1000.0;
  74478. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74479. outputLiminance += _this.hdrDecreaseRate * dt;
  74480. }
  74481. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74482. outputLiminance -= _this.hdrIncreaseRate * dt;
  74483. }
  74484. else {
  74485. outputLiminance = _this._hdrCurrentLuminance;
  74486. }
  74487. }
  74488. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74489. effect.setFloat("averageLuminance", outputLiminance);
  74490. lastTime = time;
  74491. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74492. };
  74493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74494. };
  74495. // Create lens flare post-process
  74496. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74497. var _this = this;
  74498. 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);
  74499. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74500. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74501. 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);
  74502. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74503. var resolution = new BABYLON.Vector2(0, 0);
  74504. // Lens flare
  74505. this.lensFlarePostProcess.onApply = function (effect) {
  74506. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74507. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74508. effect.setFloat("strength", _this.lensFlareStrength);
  74509. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74510. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74511. // Shift
  74512. resolution.x = _this.lensFlarePostProcess.width;
  74513. resolution.y = _this.lensFlarePostProcess.height;
  74514. effect.setVector2("resolution", resolution);
  74515. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74516. };
  74517. // Compose
  74518. 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);
  74519. 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);
  74520. this.lensFlareComposePostProcess.onApply = function (effect) {
  74521. if (!_this._scene.activeCamera) {
  74522. return;
  74523. }
  74524. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74525. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74526. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74527. // Lens start rotation matrix
  74528. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74529. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74530. 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));
  74531. camRot *= 4.0;
  74532. 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);
  74533. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74534. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74535. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74536. };
  74537. };
  74538. // Create depth-of-field post-process
  74539. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74540. var _this = this;
  74541. 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);
  74542. this.depthOfFieldPostProcess.onApply = function (effect) {
  74543. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74544. effect.setTexture("depthSampler", _this._getDepthTexture());
  74545. effect.setFloat("distance", _this.depthOfFieldDistance);
  74546. };
  74547. // Add to pipeline
  74548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74549. };
  74550. // Create motion blur post-process
  74551. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74552. var _this = this;
  74553. 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);
  74554. var motionScale = 0;
  74555. var prevViewProjection = BABYLON.Matrix.Identity();
  74556. var invViewProjection = BABYLON.Matrix.Identity();
  74557. var viewProjection = BABYLON.Matrix.Identity();
  74558. var screenSize = BABYLON.Vector2.Zero();
  74559. this.motionBlurPostProcess.onApply = function (effect) {
  74560. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74561. viewProjection.invertToRef(invViewProjection);
  74562. effect.setMatrix("inverseViewProjection", invViewProjection);
  74563. effect.setMatrix("prevViewProjection", prevViewProjection);
  74564. prevViewProjection = viewProjection;
  74565. screenSize.x = _this.motionBlurPostProcess.width;
  74566. screenSize.y = _this.motionBlurPostProcess.height;
  74567. effect.setVector2("screenSize", screenSize);
  74568. motionScale = scene.getEngine().getFps() / 60.0;
  74569. effect.setFloat("motionScale", motionScale);
  74570. effect.setFloat("motionStrength", _this.motionStrength);
  74571. effect.setTexture("depthSampler", _this._getDepthTexture());
  74572. };
  74573. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74574. };
  74575. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74576. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74577. var renderer = this._scene.enableGeometryBufferRenderer();
  74578. return renderer.getGBuffer().textures[0];
  74579. }
  74580. return this._scene.enableDepthRenderer().getDepthMap();
  74581. };
  74582. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74583. for (var i = 0; i < this._cameras.length; i++) {
  74584. var camera = this._cameras[i];
  74585. if (this.originalPostProcess) {
  74586. this.originalPostProcess.dispose(camera);
  74587. }
  74588. if (this.downSampleX4PostProcess) {
  74589. this.downSampleX4PostProcess.dispose(camera);
  74590. }
  74591. if (this.brightPassPostProcess) {
  74592. this.brightPassPostProcess.dispose(camera);
  74593. }
  74594. if (this.textureAdderPostProcess) {
  74595. this.textureAdderPostProcess.dispose(camera);
  74596. }
  74597. if (this.textureAdderFinalPostProcess) {
  74598. this.textureAdderFinalPostProcess.dispose(camera);
  74599. }
  74600. if (this.volumetricLightPostProcess) {
  74601. this.volumetricLightPostProcess.dispose(camera);
  74602. }
  74603. if (this.volumetricLightSmoothXPostProcess) {
  74604. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74605. }
  74606. if (this.volumetricLightSmoothYPostProcess) {
  74607. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74608. }
  74609. if (this.volumetricLightMergePostProces) {
  74610. this.volumetricLightMergePostProces.dispose(camera);
  74611. }
  74612. if (this.volumetricLightFinalPostProcess) {
  74613. this.volumetricLightFinalPostProcess.dispose(camera);
  74614. }
  74615. if (this.lensFlarePostProcess) {
  74616. this.lensFlarePostProcess.dispose(camera);
  74617. }
  74618. if (this.lensFlareComposePostProcess) {
  74619. this.lensFlareComposePostProcess.dispose(camera);
  74620. }
  74621. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74622. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74623. }
  74624. if (this.luminancePostProcess) {
  74625. this.luminancePostProcess.dispose(camera);
  74626. }
  74627. if (this.hdrPostProcess) {
  74628. this.hdrPostProcess.dispose(camera);
  74629. }
  74630. if (this.hdrFinalPostProcess) {
  74631. this.hdrFinalPostProcess.dispose(camera);
  74632. }
  74633. if (this.depthOfFieldPostProcess) {
  74634. this.depthOfFieldPostProcess.dispose(camera);
  74635. }
  74636. if (this.motionBlurPostProcess) {
  74637. this.motionBlurPostProcess.dispose(camera);
  74638. }
  74639. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74640. this.blurHPostProcesses[j].dispose(camera);
  74641. }
  74642. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74643. this.blurVPostProcesses[j].dispose(camera);
  74644. }
  74645. }
  74646. this.originalPostProcess = null;
  74647. this.downSampleX4PostProcess = null;
  74648. this.brightPassPostProcess = null;
  74649. this.textureAdderPostProcess = null;
  74650. this.textureAdderFinalPostProcess = null;
  74651. this.volumetricLightPostProcess = null;
  74652. this.volumetricLightSmoothXPostProcess = null;
  74653. this.volumetricLightSmoothYPostProcess = null;
  74654. this.volumetricLightMergePostProces = null;
  74655. this.volumetricLightFinalPostProcess = null;
  74656. this.lensFlarePostProcess = null;
  74657. this.lensFlareComposePostProcess = null;
  74658. this.luminancePostProcess = null;
  74659. this.hdrPostProcess = null;
  74660. this.hdrFinalPostProcess = null;
  74661. this.depthOfFieldPostProcess = null;
  74662. this.motionBlurPostProcess = null;
  74663. this.luminanceDownSamplePostProcesses = [];
  74664. this.blurHPostProcesses = [];
  74665. this.blurVPostProcesses = [];
  74666. };
  74667. /**
  74668. * Dispose of the pipeline and stop all post processes
  74669. */
  74670. StandardRenderingPipeline.prototype.dispose = function () {
  74671. this._disposePostProcesses();
  74672. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74673. _super.prototype.dispose.call(this);
  74674. };
  74675. /**
  74676. * Serialize the rendering pipeline (Used when exporting)
  74677. * @returns the serialized object
  74678. */
  74679. StandardRenderingPipeline.prototype.serialize = function () {
  74680. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74681. if (this.sourceLight) {
  74682. serializationObject.sourceLightId = this.sourceLight.id;
  74683. }
  74684. serializationObject.customType = "StandardRenderingPipeline";
  74685. return serializationObject;
  74686. };
  74687. /**
  74688. * Parse the serialized pipeline
  74689. * @param source Source pipeline.
  74690. * @param scene The scene to load the pipeline to.
  74691. * @param rootUrl The URL of the serialized pipeline.
  74692. * @returns An instantiated pipeline from the serialized object.
  74693. */
  74694. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74695. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74696. if (source.sourceLightId) {
  74697. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74698. }
  74699. return p;
  74700. };
  74701. // Luminance steps
  74702. StandardRenderingPipeline.LuminanceSteps = 6;
  74703. __decorate([
  74704. BABYLON.serialize()
  74705. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74706. __decorate([
  74707. BABYLON.serialize()
  74708. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74709. __decorate([
  74710. BABYLON.serialize()
  74711. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74712. __decorate([
  74713. BABYLON.serialize()
  74714. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74715. __decorate([
  74716. BABYLON.serializeAsTexture("lensTexture")
  74717. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74718. __decorate([
  74719. BABYLON.serialize()
  74720. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74721. __decorate([
  74722. BABYLON.serialize()
  74723. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74724. __decorate([
  74725. BABYLON.serialize()
  74726. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74727. __decorate([
  74728. BABYLON.serialize()
  74729. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74730. __decorate([
  74731. BABYLON.serialize()
  74732. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74733. __decorate([
  74734. BABYLON.serialize()
  74735. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74736. __decorate([
  74737. BABYLON.serializeAsTexture("lensColorTexture")
  74738. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74739. __decorate([
  74740. BABYLON.serialize()
  74741. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74742. __decorate([
  74743. BABYLON.serialize()
  74744. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74745. __decorate([
  74746. BABYLON.serialize()
  74747. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74748. __decorate([
  74749. BABYLON.serialize()
  74750. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74751. __decorate([
  74752. BABYLON.serializeAsTexture("lensStarTexture")
  74753. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74754. __decorate([
  74755. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74756. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74757. __decorate([
  74758. BABYLON.serialize()
  74759. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74760. __decorate([
  74761. BABYLON.serialize()
  74762. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74763. __decorate([
  74764. BABYLON.serialize()
  74765. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74766. __decorate([
  74767. BABYLON.serialize()
  74768. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74769. __decorate([
  74770. BABYLON.serialize()
  74771. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74772. __decorate([
  74773. BABYLON.serialize()
  74774. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74775. __decorate([
  74776. BABYLON.serialize()
  74777. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74778. __decorate([
  74779. BABYLON.serialize()
  74780. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74781. __decorate([
  74782. BABYLON.serialize()
  74783. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74784. __decorate([
  74785. BABYLON.serialize()
  74786. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74787. __decorate([
  74788. BABYLON.serialize()
  74789. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74790. __decorate([
  74791. BABYLON.serialize()
  74792. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74793. return StandardRenderingPipeline;
  74794. }(BABYLON.PostProcessRenderPipeline));
  74795. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74796. })(BABYLON || (BABYLON = {}));
  74797. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74798. var BABYLON;
  74799. (function (BABYLON) {
  74800. var FxaaPostProcess = /** @class */ (function (_super) {
  74801. __extends(FxaaPostProcess, _super);
  74802. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74803. if (camera === void 0) { camera = null; }
  74804. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74805. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74806. var defines = _this._getDefines();
  74807. _this.updateEffect(defines);
  74808. _this.onApplyObservable.add(function (effect) {
  74809. var texelSize = _this.texelSize;
  74810. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74811. });
  74812. return _this;
  74813. }
  74814. FxaaPostProcess.prototype._getDefines = function () {
  74815. var engine = this.getEngine();
  74816. if (!engine) {
  74817. return null;
  74818. }
  74819. var glInfo = engine.getGlInfo();
  74820. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74821. return "#define MALI 1\n";
  74822. }
  74823. return null;
  74824. };
  74825. return FxaaPostProcess;
  74826. }(BABYLON.PostProcess));
  74827. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74828. })(BABYLON || (BABYLON = {}));
  74829. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74830. var BABYLON;
  74831. (function (BABYLON) {
  74832. /**
  74833. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74834. */
  74835. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74836. __extends(ChromaticAberrationPostProcess, _super);
  74837. /**
  74838. * Creates a new instance ChromaticAberrationPostProcess
  74839. * @param name The name of the effect.
  74840. * @param screenWidth The width of the screen to apply the effect on.
  74841. * @param screenHeight The height of the screen to apply the effect on.
  74842. * @param options The required width/height ratio to downsize to before computing the render pass.
  74843. * @param camera The camera to apply the render pass to.
  74844. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74845. * @param engine The engine which the post process will be applied. (default: current engine)
  74846. * @param reusable If the post process can be reused on the same frame. (default: false)
  74847. * @param textureType Type of textures used when performing the post process. (default: 0)
  74848. * @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)
  74849. */
  74850. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74851. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74852. if (blockCompilation === void 0) { blockCompilation = false; }
  74853. 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;
  74854. /**
  74855. * The amount of seperation of rgb channels (default: 30)
  74856. */
  74857. _this.aberrationAmount = 30;
  74858. /**
  74859. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74860. */
  74861. _this.radialIntensity = 0;
  74862. /**
  74863. * 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))
  74864. */
  74865. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74866. /**
  74867. * 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))
  74868. */
  74869. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74870. _this.onApplyObservable.add(function (effect) {
  74871. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74872. effect.setFloat('screen_width', screenWidth);
  74873. effect.setFloat('screen_height', screenHeight);
  74874. effect.setFloat('radialIntensity', _this.radialIntensity);
  74875. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74876. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74877. });
  74878. return _this;
  74879. }
  74880. return ChromaticAberrationPostProcess;
  74881. }(BABYLON.PostProcess));
  74882. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74883. })(BABYLON || (BABYLON = {}));
  74884. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74885. var BABYLON;
  74886. (function (BABYLON) {
  74887. /**
  74888. * The GrainPostProcess adds noise to the image at mid luminance levels
  74889. */
  74890. var GrainPostProcess = /** @class */ (function (_super) {
  74891. __extends(GrainPostProcess, _super);
  74892. /**
  74893. * Creates a new instance of @see GrainPostProcess
  74894. * @param name The name of the effect.
  74895. * @param options The required width/height ratio to downsize to before computing the render pass.
  74896. * @param camera The camera to apply the render pass to.
  74897. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74898. * @param engine The engine which the post process will be applied. (default: current engine)
  74899. * @param reusable If the post process can be reused on the same frame. (default: false)
  74900. * @param textureType Type of textures used when performing the post process. (default: 0)
  74901. * @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)
  74902. */
  74903. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74904. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74905. if (blockCompilation === void 0) { blockCompilation = false; }
  74906. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74907. /**
  74908. * The intensity of the grain added (default: 30)
  74909. */
  74910. _this.intensity = 30;
  74911. /**
  74912. * If the grain should be randomized on every frame
  74913. */
  74914. _this.animated = false;
  74915. _this.onApplyObservable.add(function (effect) {
  74916. effect.setFloat('intensity', _this.intensity);
  74917. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74918. });
  74919. return _this;
  74920. }
  74921. return GrainPostProcess;
  74922. }(BABYLON.PostProcess));
  74923. BABYLON.GrainPostProcess = GrainPostProcess;
  74924. })(BABYLON || (BABYLON = {}));
  74925. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74926. var BABYLON;
  74927. (function (BABYLON) {
  74928. /**
  74929. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74930. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74931. */
  74932. var SharpenPostProcess = /** @class */ (function (_super) {
  74933. __extends(SharpenPostProcess, _super);
  74934. /**
  74935. * Creates a new instance ConvolutionPostProcess
  74936. * @param name The name of the effect.
  74937. * @param options The required width/height ratio to downsize to before computing the render pass.
  74938. * @param camera The camera to apply the render pass to.
  74939. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74940. * @param engine The engine which the post process will be applied. (default: current engine)
  74941. * @param reusable If the post process can be reused on the same frame. (default: false)
  74942. * @param textureType Type of textures used when performing the post process. (default: 0)
  74943. * @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)
  74944. */
  74945. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74946. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74947. if (blockCompilation === void 0) { blockCompilation = false; }
  74948. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74949. /**
  74950. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74951. */
  74952. _this.colorAmount = 1.0;
  74953. /**
  74954. * How much sharpness should be applied (default: 0.3)
  74955. */
  74956. _this.edgeAmount = 0.3;
  74957. _this.onApply = function (effect) {
  74958. effect.setFloat2("screenSize", _this.width, _this.height);
  74959. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74960. };
  74961. return _this;
  74962. }
  74963. return SharpenPostProcess;
  74964. }(BABYLON.PostProcess));
  74965. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74966. })(BABYLON || (BABYLON = {}));
  74967. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74968. var BABYLON;
  74969. (function (BABYLON) {
  74970. /**
  74971. * The Blur Post Process which blurs an image based on a kernel and direction.
  74972. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74973. */
  74974. var BlurPostProcess = /** @class */ (function (_super) {
  74975. __extends(BlurPostProcess, _super);
  74976. /**
  74977. * Creates a new instance BlurPostProcess
  74978. * @param name The name of the effect.
  74979. * @param direction The direction in which to blur the image.
  74980. * @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.
  74981. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74982. * @param camera The camera to apply the render pass to.
  74983. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74984. * @param engine The engine which the post process will be applied. (default: current engine)
  74985. * @param reusable If the post process can be reused on the same frame. (default: false)
  74986. * @param textureType Type of textures used when performing the post process. (default: 0)
  74987. * @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)
  74988. */
  74989. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74990. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74991. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74992. if (defines === void 0) { defines = ""; }
  74993. if (blockCompilation === void 0) { blockCompilation = false; }
  74994. 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;
  74995. _this.direction = direction;
  74996. _this.blockCompilation = blockCompilation;
  74997. _this._packedFloat = false;
  74998. _this._staticDefines = "";
  74999. _this._staticDefines = defines;
  75000. _this.onApplyObservable.add(function (effect) {
  75001. if (_this._outputTexture) {
  75002. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75003. }
  75004. else {
  75005. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75006. }
  75007. });
  75008. _this.kernel = kernel;
  75009. return _this;
  75010. }
  75011. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75012. /**
  75013. * Gets the length in pixels of the blur sample region
  75014. */
  75015. get: function () {
  75016. return this._idealKernel;
  75017. },
  75018. /**
  75019. * Sets the length in pixels of the blur sample region
  75020. */
  75021. set: function (v) {
  75022. if (this._idealKernel === v) {
  75023. return;
  75024. }
  75025. v = Math.max(v, 1);
  75026. this._idealKernel = v;
  75027. this._kernel = this._nearestBestKernel(v);
  75028. if (!this.blockCompilation) {
  75029. this._updateParameters();
  75030. }
  75031. },
  75032. enumerable: true,
  75033. configurable: true
  75034. });
  75035. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75036. /**
  75037. * Gets wether or not the blur is unpacking/repacking floats
  75038. */
  75039. get: function () {
  75040. return this._packedFloat;
  75041. },
  75042. /**
  75043. * Sets wether or not the blur needs to unpack/repack floats
  75044. */
  75045. set: function (v) {
  75046. if (this._packedFloat === v) {
  75047. return;
  75048. }
  75049. this._packedFloat = v;
  75050. if (!this.blockCompilation) {
  75051. this._updateParameters();
  75052. }
  75053. },
  75054. enumerable: true,
  75055. configurable: true
  75056. });
  75057. /**
  75058. * Updates the effect with the current post process compile time values and recompiles the shader.
  75059. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75060. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75061. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75062. * @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
  75063. * @param onCompiled Called when the shader has been compiled.
  75064. * @param onError Called if there is an error when compiling a shader.
  75065. */
  75066. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75067. if (defines === void 0) { defines = null; }
  75068. if (uniforms === void 0) { uniforms = null; }
  75069. if (samplers === void 0) { samplers = null; }
  75070. this._updateParameters(onCompiled, onError);
  75071. };
  75072. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75073. // Generate sampling offsets and weights
  75074. var N = this._kernel;
  75075. var centerIndex = (N - 1) / 2;
  75076. // Generate Gaussian sampling weights over kernel
  75077. var offsets = [];
  75078. var weights = [];
  75079. var totalWeight = 0;
  75080. for (var i = 0; i < N; i++) {
  75081. var u = i / (N - 1);
  75082. var w = this._gaussianWeight(u * 2.0 - 1);
  75083. offsets[i] = (i - centerIndex);
  75084. weights[i] = w;
  75085. totalWeight += w;
  75086. }
  75087. // Normalize weights
  75088. for (var i = 0; i < weights.length; i++) {
  75089. weights[i] /= totalWeight;
  75090. }
  75091. // Optimize: combine samples to take advantage of hardware linear sampling
  75092. // Walk from left to center, combining pairs (symmetrically)
  75093. var linearSamplingWeights = [];
  75094. var linearSamplingOffsets = [];
  75095. var linearSamplingMap = [];
  75096. for (var i = 0; i <= centerIndex; i += 2) {
  75097. var j = Math.min(i + 1, Math.floor(centerIndex));
  75098. var singleCenterSample = i === j;
  75099. if (singleCenterSample) {
  75100. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75101. }
  75102. else {
  75103. var sharedCell = j === centerIndex;
  75104. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75105. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75106. if (offsetLinear === 0) {
  75107. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75108. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75109. }
  75110. else {
  75111. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75112. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75113. }
  75114. }
  75115. }
  75116. for (var i = 0; i < linearSamplingMap.length; i++) {
  75117. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75118. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75119. }
  75120. // Replace with optimized
  75121. offsets = linearSamplingOffsets;
  75122. weights = linearSamplingWeights;
  75123. // Generate shaders
  75124. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75125. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75126. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75127. var defines = "";
  75128. defines += this._staticDefines;
  75129. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75130. if (this._staticDefines.indexOf("DOF") != -1) {
  75131. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75132. varyingCount--;
  75133. }
  75134. for (var i = 0; i < varyingCount; i++) {
  75135. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75136. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75137. }
  75138. var depCount = 0;
  75139. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75140. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75141. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75142. depCount++;
  75143. }
  75144. if (this.packedFloat) {
  75145. defines += "#define PACKEDFLOAT 1";
  75146. }
  75147. this.blockCompilation = false;
  75148. _super.prototype.updateEffect.call(this, defines, null, null, {
  75149. varyingCount: varyingCount,
  75150. depCount: depCount
  75151. }, onCompiled, onError);
  75152. };
  75153. /**
  75154. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75155. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75156. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75157. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75158. * The gaps between physical kernels are compensated for in the weighting of the samples
  75159. * @param idealKernel Ideal blur kernel.
  75160. * @return Nearest best kernel.
  75161. */
  75162. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75163. var v = Math.round(idealKernel);
  75164. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75165. var k = _a[_i];
  75166. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75167. return Math.max(k, 3);
  75168. }
  75169. }
  75170. return Math.max(v, 3);
  75171. };
  75172. /**
  75173. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75174. * @param x The point on the Gaussian distribution to sample.
  75175. * @return the value of the Gaussian function at x.
  75176. */
  75177. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75178. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75179. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75180. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75181. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75182. // truncated at around 1.3% of peak strength.
  75183. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75184. var sigma = (1 / 3);
  75185. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75186. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75187. var weight = (1.0 / denominator) * Math.exp(exponent);
  75188. return weight;
  75189. };
  75190. /**
  75191. * Generates a string that can be used as a floating point number in GLSL.
  75192. * @param x Value to print.
  75193. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75194. * @return GLSL float string.
  75195. */
  75196. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75197. if (decimalFigures === void 0) { decimalFigures = 8; }
  75198. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75199. };
  75200. return BlurPostProcess;
  75201. }(BABYLON.PostProcess));
  75202. BABYLON.BlurPostProcess = BlurPostProcess;
  75203. })(BABYLON || (BABYLON = {}));
  75204. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75205. var BABYLON;
  75206. (function (BABYLON) {
  75207. /**
  75208. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75209. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75210. * based on samples that have a large difference in distance than the center pixel.
  75211. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75212. */
  75213. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75214. __extends(DepthOfFieldBlurPostProcess, _super);
  75215. /**
  75216. * Creates a new instance CircleOfConfusionPostProcess
  75217. * @param name The name of the effect.
  75218. * @param scene The scene the effect belongs to.
  75219. * @param direction The direction the blur should be applied.
  75220. * @param kernel The size of the kernel used to blur.
  75221. * @param options The required width/height ratio to downsize to before computing the render pass.
  75222. * @param camera The camera to apply the render pass to.
  75223. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75224. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75225. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75226. * @param engine The engine which the post process will be applied. (default: current engine)
  75227. * @param reusable If the post process can be reused on the same frame. (default: false)
  75228. * @param textureType Type of textures used when performing the post process. (default: 0)
  75229. * @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)
  75230. */
  75231. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75232. if (imageToBlur === void 0) { imageToBlur = null; }
  75233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75234. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75235. if (blockCompilation === void 0) { blockCompilation = false; }
  75236. 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;
  75237. _this.direction = direction;
  75238. _this.onApplyObservable.add(function (effect) {
  75239. if (imageToBlur != null) {
  75240. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75241. }
  75242. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75243. if (scene.activeCamera) {
  75244. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75245. }
  75246. });
  75247. return _this;
  75248. }
  75249. return DepthOfFieldBlurPostProcess;
  75250. }(BABYLON.BlurPostProcess));
  75251. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75252. })(BABYLON || (BABYLON = {}));
  75253. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75254. var BABYLON;
  75255. (function (BABYLON) {
  75256. /**
  75257. * Options to be set when merging outputs from the default pipeline.
  75258. */
  75259. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75260. function DepthOfFieldMergePostProcessOptions() {
  75261. }
  75262. return DepthOfFieldMergePostProcessOptions;
  75263. }());
  75264. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75265. /**
  75266. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75267. */
  75268. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75269. __extends(DepthOfFieldMergePostProcess, _super);
  75270. /**
  75271. * Creates a new instance of DepthOfFieldMergePostProcess
  75272. * @param name The name of the effect.
  75273. * @param originalFromInput Post process which's input will be used for the merge.
  75274. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75275. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75276. * @param options The required width/height ratio to downsize to before computing the render pass.
  75277. * @param camera The camera to apply the render pass to.
  75278. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75279. * @param engine The engine which the post process will be applied. (default: current engine)
  75280. * @param reusable If the post process can be reused on the same frame. (default: false)
  75281. * @param textureType Type of textures used when performing the post process. (default: 0)
  75282. * @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)
  75283. */
  75284. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75285. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75286. if (blockCompilation === void 0) { blockCompilation = false; }
  75287. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75288. _this.blurSteps = blurSteps;
  75289. _this.onApplyObservable.add(function (effect) {
  75290. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75291. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75292. blurSteps.forEach(function (step, index) {
  75293. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75294. });
  75295. });
  75296. if (!blockCompilation) {
  75297. _this.updateEffect();
  75298. }
  75299. return _this;
  75300. }
  75301. /**
  75302. * Updates the effect with the current post process compile time values and recompiles the shader.
  75303. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75304. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75305. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75306. * @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
  75307. * @param onCompiled Called when the shader has been compiled.
  75308. * @param onError Called if there is an error when compiling a shader.
  75309. */
  75310. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75311. if (defines === void 0) { defines = null; }
  75312. if (uniforms === void 0) { uniforms = null; }
  75313. if (samplers === void 0) { samplers = null; }
  75314. if (!defines) {
  75315. defines = "";
  75316. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75317. }
  75318. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75319. };
  75320. return DepthOfFieldMergePostProcess;
  75321. }(BABYLON.PostProcess));
  75322. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75323. })(BABYLON || (BABYLON = {}));
  75324. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75325. var BABYLON;
  75326. (function (BABYLON) {
  75327. /**
  75328. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75329. */
  75330. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75331. __extends(CircleOfConfusionPostProcess, _super);
  75332. /**
  75333. * Creates a new instance CircleOfConfusionPostProcess
  75334. * @param name The name of the effect.
  75335. * @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.
  75336. * @param options The required width/height ratio to downsize to before computing the render pass.
  75337. * @param camera The camera to apply the render pass to.
  75338. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75339. * @param engine The engine which the post process will be applied. (default: current engine)
  75340. * @param reusable If the post process can be reused on the same frame. (default: false)
  75341. * @param textureType Type of textures used when performing the post process. (default: 0)
  75342. * @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)
  75343. */
  75344. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75345. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75346. if (blockCompilation === void 0) { blockCompilation = false; }
  75347. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75348. /**
  75349. * 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.
  75350. */
  75351. _this.lensSize = 50;
  75352. /**
  75353. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75354. */
  75355. _this.fStop = 1.4;
  75356. /**
  75357. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75358. */
  75359. _this.focusDistance = 2000;
  75360. /**
  75361. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75362. */
  75363. _this.focalLength = 50;
  75364. _this._depthTexture = null;
  75365. _this._depthTexture = depthTexture;
  75366. _this.onApplyObservable.add(function (effect) {
  75367. if (!_this._depthTexture) {
  75368. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75369. return;
  75370. }
  75371. effect.setTexture("depthSampler", _this._depthTexture);
  75372. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75373. var aperture = _this.lensSize / _this.fStop;
  75374. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75375. effect.setFloat('focusDistance', _this.focusDistance);
  75376. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75377. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75378. });
  75379. return _this;
  75380. }
  75381. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75382. /**
  75383. * 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.
  75384. */
  75385. set: function (value) {
  75386. this._depthTexture = value;
  75387. },
  75388. enumerable: true,
  75389. configurable: true
  75390. });
  75391. return CircleOfConfusionPostProcess;
  75392. }(BABYLON.PostProcess));
  75393. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75394. })(BABYLON || (BABYLON = {}));
  75395. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75396. var BABYLON;
  75397. (function (BABYLON) {
  75398. /**
  75399. * Specifies the level of max blur that should be applied when using the depth of field effect
  75400. */
  75401. var DepthOfFieldEffectBlurLevel;
  75402. (function (DepthOfFieldEffectBlurLevel) {
  75403. /**
  75404. * Subtle blur
  75405. */
  75406. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75407. /**
  75408. * Medium blur
  75409. */
  75410. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75411. /**
  75412. * Large blur
  75413. */
  75414. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75415. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75416. ;
  75417. /**
  75418. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75419. */
  75420. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75421. __extends(DepthOfFieldEffect, _super);
  75422. /**
  75423. * Creates a new instance DepthOfFieldEffect
  75424. * @param scene The scene the effect belongs to.
  75425. * @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.
  75426. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75427. * @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)
  75428. */
  75429. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75430. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75431. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75432. if (blockCompilation === void 0) { blockCompilation = false; }
  75433. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75434. return _this._effects;
  75435. }, true) || this;
  75436. /**
  75437. * Internal post processes in depth of field effect
  75438. */
  75439. _this._effects = [];
  75440. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75441. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75442. // 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)
  75443. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75444. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75445. _this._depthOfFieldBlurY = [];
  75446. _this._depthOfFieldBlurX = [];
  75447. var blurCount = 1;
  75448. var kernelSize = 15;
  75449. switch (blurLevel) {
  75450. case DepthOfFieldEffectBlurLevel.High: {
  75451. blurCount = 3;
  75452. kernelSize = 51;
  75453. break;
  75454. }
  75455. case DepthOfFieldEffectBlurLevel.Medium: {
  75456. blurCount = 2;
  75457. kernelSize = 31;
  75458. break;
  75459. }
  75460. default: {
  75461. kernelSize = 15;
  75462. blurCount = 1;
  75463. break;
  75464. }
  75465. }
  75466. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75467. var ratio = 1.0;
  75468. for (var i = 0; i < blurCount; i++) {
  75469. 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);
  75470. blurY.autoClear = false;
  75471. ratio = 0.75 / Math.pow(2, i);
  75472. 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);
  75473. blurX.autoClear = false;
  75474. _this._depthOfFieldBlurY.push(blurY);
  75475. _this._depthOfFieldBlurX.push(blurX);
  75476. }
  75477. // Set all post processes on the effect.
  75478. _this._effects = [_this._circleOfConfusion];
  75479. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75480. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75481. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75482. }
  75483. // Merge blurred images with original image based on circleOfConfusion
  75484. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75485. _this._dofMerge.autoClear = false;
  75486. _this._effects.push(_this._dofMerge);
  75487. return _this;
  75488. }
  75489. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75490. get: function () {
  75491. return this._circleOfConfusion.focalLength;
  75492. },
  75493. /**
  75494. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75495. */
  75496. set: function (value) {
  75497. this._circleOfConfusion.focalLength = value;
  75498. },
  75499. enumerable: true,
  75500. configurable: true
  75501. });
  75502. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75503. get: function () {
  75504. return this._circleOfConfusion.fStop;
  75505. },
  75506. /**
  75507. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75508. */
  75509. set: function (value) {
  75510. this._circleOfConfusion.fStop = value;
  75511. },
  75512. enumerable: true,
  75513. configurable: true
  75514. });
  75515. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75516. get: function () {
  75517. return this._circleOfConfusion.focusDistance;
  75518. },
  75519. /**
  75520. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75521. */
  75522. set: function (value) {
  75523. this._circleOfConfusion.focusDistance = value;
  75524. },
  75525. enumerable: true,
  75526. configurable: true
  75527. });
  75528. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75529. get: function () {
  75530. return this._circleOfConfusion.lensSize;
  75531. },
  75532. /**
  75533. * 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.
  75534. */
  75535. set: function (value) {
  75536. this._circleOfConfusion.lensSize = value;
  75537. },
  75538. enumerable: true,
  75539. configurable: true
  75540. });
  75541. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75542. /**
  75543. * 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.
  75544. */
  75545. set: function (value) {
  75546. this._circleOfConfusion.depthTexture = value;
  75547. },
  75548. enumerable: true,
  75549. configurable: true
  75550. });
  75551. /**
  75552. * Disposes each of the internal effects for a given camera.
  75553. * @param camera The camera to dispose the effect on.
  75554. */
  75555. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75556. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75557. this._effects[effectIndex].dispose(camera);
  75558. }
  75559. };
  75560. /**
  75561. * Internal
  75562. */
  75563. DepthOfFieldEffect.prototype._updateEffects = function () {
  75564. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75565. this._effects[effectIndex].updateEffect();
  75566. }
  75567. };
  75568. /**
  75569. * Internal
  75570. * @returns if all the contained post processes are ready.
  75571. */
  75572. DepthOfFieldEffect.prototype._isReady = function () {
  75573. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75574. if (!this._effects[effectIndex].isReady()) {
  75575. return false;
  75576. }
  75577. }
  75578. return true;
  75579. };
  75580. return DepthOfFieldEffect;
  75581. }(BABYLON.PostProcessRenderEffect));
  75582. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75583. })(BABYLON || (BABYLON = {}));
  75584. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75585. var BABYLON;
  75586. (function (BABYLON) {
  75587. /**
  75588. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75589. */
  75590. var BloomMergePostProcess = /** @class */ (function (_super) {
  75591. __extends(BloomMergePostProcess, _super);
  75592. /**
  75593. * Creates a new instance of @see BloomMergePostProcess
  75594. * @param name The name of the effect.
  75595. * @param originalFromInput Post process which's input will be used for the merge.
  75596. * @param blurred Blurred highlights post process which's output will be used.
  75597. * @param weight Weight of the bloom to be added to the original input.
  75598. * @param options The required width/height ratio to downsize to before computing the render pass.
  75599. * @param camera The camera to apply the render pass to.
  75600. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75601. * @param engine The engine which the post process will be applied. (default: current engine)
  75602. * @param reusable If the post process can be reused on the same frame. (default: false)
  75603. * @param textureType Type of textures used when performing the post process. (default: 0)
  75604. * @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)
  75605. */
  75606. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75607. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75608. if (blockCompilation === void 0) { blockCompilation = false; }
  75609. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75610. _this.weight = weight;
  75611. _this.onApplyObservable.add(function (effect) {
  75612. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75613. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75614. effect.setFloat("bloomWeight", _this.weight);
  75615. });
  75616. if (!blockCompilation) {
  75617. _this.updateEffect();
  75618. }
  75619. return _this;
  75620. }
  75621. return BloomMergePostProcess;
  75622. }(BABYLON.PostProcess));
  75623. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75624. })(BABYLON || (BABYLON = {}));
  75625. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75626. var BABYLON;
  75627. (function (BABYLON) {
  75628. /**
  75629. * 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.
  75630. */
  75631. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75632. __extends(ExtractHighlightsPostProcess, _super);
  75633. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75634. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75635. if (blockCompilation === void 0) { blockCompilation = false; }
  75636. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75637. /**
  75638. * The luminance threshold, pixels below this value will be set to black.
  75639. */
  75640. _this.threshold = 0.9;
  75641. /**
  75642. * Internal
  75643. */
  75644. _this._exposure = 1;
  75645. /**
  75646. * Post process which has the input texture to be used when performing highlight extraction
  75647. */
  75648. _this._inputPostProcess = null;
  75649. _this.onApplyObservable.add(function (effect) {
  75650. if (_this._inputPostProcess) {
  75651. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75652. }
  75653. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75654. effect.setFloat('exposure', _this._exposure);
  75655. });
  75656. return _this;
  75657. }
  75658. return ExtractHighlightsPostProcess;
  75659. }(BABYLON.PostProcess));
  75660. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75661. })(BABYLON || (BABYLON = {}));
  75662. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75663. var BABYLON;
  75664. (function (BABYLON) {
  75665. /**
  75666. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75667. */
  75668. var BloomEffect = /** @class */ (function (_super) {
  75669. __extends(BloomEffect, _super);
  75670. /**
  75671. * Creates a new instance of @see BloomEffect
  75672. * @param scene The scene the effect belongs to.
  75673. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75674. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75675. * @param bloomWeight The the strength of bloom.
  75676. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75677. * @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)
  75678. */
  75679. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75680. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75681. if (blockCompilation === void 0) { blockCompilation = false; }
  75682. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75683. return _this._effects;
  75684. }, true) || this;
  75685. _this.bloomScale = bloomScale;
  75686. /**
  75687. * Internal
  75688. */
  75689. _this._effects = [];
  75690. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75691. _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);
  75692. _this._blurX.alwaysForcePOT = true;
  75693. _this._blurX.autoClear = false;
  75694. _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);
  75695. _this._blurY.alwaysForcePOT = true;
  75696. _this._blurY.autoClear = false;
  75697. _this.kernel = bloomKernel;
  75698. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75699. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75700. _this._merge.autoClear = false;
  75701. _this._effects.push(_this._merge);
  75702. return _this;
  75703. }
  75704. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75705. /**
  75706. * The luminance threshold to find bright areas of the image to bloom.
  75707. */
  75708. get: function () {
  75709. return this._downscale.threshold;
  75710. },
  75711. set: function (value) {
  75712. this._downscale.threshold = value;
  75713. },
  75714. enumerable: true,
  75715. configurable: true
  75716. });
  75717. Object.defineProperty(BloomEffect.prototype, "weight", {
  75718. /**
  75719. * The strength of the bloom.
  75720. */
  75721. get: function () {
  75722. return this._merge.weight;
  75723. },
  75724. set: function (value) {
  75725. this._merge.weight = value;
  75726. },
  75727. enumerable: true,
  75728. configurable: true
  75729. });
  75730. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75731. /**
  75732. * Specifies the size of the bloom blur kernel, relative to the final output size
  75733. */
  75734. get: function () {
  75735. return this._blurX.kernel / this.bloomScale;
  75736. },
  75737. set: function (value) {
  75738. this._blurX.kernel = value * this.bloomScale;
  75739. this._blurY.kernel = value * this.bloomScale;
  75740. },
  75741. enumerable: true,
  75742. configurable: true
  75743. });
  75744. /**
  75745. * Disposes each of the internal effects for a given camera.
  75746. * @param camera The camera to dispose the effect on.
  75747. */
  75748. BloomEffect.prototype.disposeEffects = function (camera) {
  75749. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75750. this._effects[effectIndex].dispose(camera);
  75751. }
  75752. };
  75753. /**
  75754. * Internal
  75755. */
  75756. BloomEffect.prototype._updateEffects = function () {
  75757. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75758. this._effects[effectIndex].updateEffect();
  75759. }
  75760. };
  75761. /**
  75762. * Internal
  75763. * @returns if all the contained post processes are ready.
  75764. */
  75765. BloomEffect.prototype._isReady = function () {
  75766. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75767. if (!this._effects[effectIndex].isReady()) {
  75768. return false;
  75769. }
  75770. }
  75771. return true;
  75772. };
  75773. return BloomEffect;
  75774. }(BABYLON.PostProcessRenderEffect));
  75775. BABYLON.BloomEffect = BloomEffect;
  75776. })(BABYLON || (BABYLON = {}));
  75777. //# sourceMappingURL=babylon.bloomEffect.js.map
  75778. var BABYLON;
  75779. (function (BABYLON) {
  75780. /**
  75781. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75782. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75783. */
  75784. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75785. __extends(DefaultRenderingPipeline, _super);
  75786. /**
  75787. * @constructor
  75788. * @param {string} name - The rendering pipeline name (default: "")
  75789. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  75790. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  75791. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  75792. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  75793. */
  75794. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75795. if (name === void 0) { name = ""; }
  75796. if (hdr === void 0) { hdr = true; }
  75797. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  75798. if (automaticBuild === void 0) { automaticBuild = true; }
  75799. var _this = _super.call(this, scene.getEngine(), name) || this;
  75800. _this._originalCameras = [];
  75801. /**
  75802. * ID of the sharpen post process,
  75803. */
  75804. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75805. /**
  75806. * ID of the image processing post process;
  75807. */
  75808. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75809. /**
  75810. * ID of the Fast Approximate Anti-Aliasing post process;
  75811. */
  75812. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75813. /**
  75814. * ID of the chromatic aberration post process,
  75815. */
  75816. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75817. /**
  75818. * ID of the grain post process
  75819. */
  75820. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75821. /**
  75822. * Glow post process which adds a glow to emmisive areas of the image
  75823. */
  75824. _this._glowLayer = null;
  75825. /**
  75826. * Animations which can be used to tweak settings over a period of time
  75827. */
  75828. _this.animations = [];
  75829. _this._imageProcessingConfigurationObserver = null;
  75830. // Values
  75831. _this._sharpenEnabled = false;
  75832. _this._bloomEnabled = false;
  75833. _this._depthOfFieldEnabled = false;
  75834. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75835. _this._fxaaEnabled = false;
  75836. _this._imageProcessingEnabled = true;
  75837. _this._bloomScale = 0.5;
  75838. _this._chromaticAberrationEnabled = false;
  75839. _this._grainEnabled = false;
  75840. _this._buildAllowed = true;
  75841. _this._resizeObserver = null;
  75842. _this._hardwareScaleLevel = 1.0;
  75843. _this._bloomKernel = 64;
  75844. /**
  75845. * Specifies the weight of the bloom in the final rendering
  75846. */
  75847. _this._bloomWeight = 0.15;
  75848. /**
  75849. * Specifies the luma threshold for the area that will be blurred by the bloom
  75850. */
  75851. _this._bloomThreshold = 0.9;
  75852. _this._samples = 1;
  75853. _this._hasCleared = false;
  75854. _this._prevPostProcess = null;
  75855. _this._prevPrevPostProcess = null;
  75856. _this._cameras = cameras || scene.cameras;
  75857. _this._originalCameras = _this._cameras.slice();
  75858. _this._buildAllowed = automaticBuild;
  75859. // Initialize
  75860. _this._scene = scene;
  75861. var caps = _this._scene.getEngine().getCaps();
  75862. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75863. // Misc
  75864. if (_this._hdr) {
  75865. if (caps.textureHalfFloatRender) {
  75866. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75867. }
  75868. else if (caps.textureFloatRender) {
  75869. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75870. }
  75871. }
  75872. else {
  75873. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75874. }
  75875. // Attach
  75876. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75877. var engine = _this._scene.getEngine();
  75878. // Create post processes before hand so they can be modified before enabled.
  75879. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75880. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75881. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75882. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75883. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75884. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75885. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75886. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75887. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75888. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75889. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75890. _this.bloomKernel = _this.bloomKernel;
  75891. });
  75892. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75893. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75894. });
  75895. _this._buildPipeline();
  75896. return _this;
  75897. }
  75898. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75899. get: function () {
  75900. return this._sharpenEnabled;
  75901. },
  75902. /**
  75903. * Enable or disable the sharpen process from the pipeline
  75904. */
  75905. set: function (enabled) {
  75906. if (this._sharpenEnabled === enabled) {
  75907. return;
  75908. }
  75909. this._sharpenEnabled = enabled;
  75910. this._buildPipeline();
  75911. },
  75912. enumerable: true,
  75913. configurable: true
  75914. });
  75915. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75916. /**
  75917. * Specifies the size of the bloom blur kernel, relative to the final output size
  75918. */
  75919. get: function () {
  75920. return this._bloomKernel;
  75921. },
  75922. set: function (value) {
  75923. this._bloomKernel = value;
  75924. this.bloom.kernel = value / this._hardwareScaleLevel;
  75925. },
  75926. enumerable: true,
  75927. configurable: true
  75928. });
  75929. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75930. get: function () {
  75931. return this._bloomWeight;
  75932. },
  75933. /**
  75934. * The strength of the bloom.
  75935. */
  75936. set: function (value) {
  75937. if (this._bloomWeight === value) {
  75938. return;
  75939. }
  75940. this.bloom.weight = value;
  75941. this._bloomWeight = value;
  75942. },
  75943. enumerable: true,
  75944. configurable: true
  75945. });
  75946. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75947. get: function () {
  75948. return this._bloomThreshold;
  75949. },
  75950. /**
  75951. * The strength of the bloom.
  75952. */
  75953. set: function (value) {
  75954. if (this._bloomThreshold === value) {
  75955. return;
  75956. }
  75957. this.bloom.threshold = value;
  75958. this._bloomThreshold = value;
  75959. },
  75960. enumerable: true,
  75961. configurable: true
  75962. });
  75963. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75964. get: function () {
  75965. return this._bloomScale;
  75966. },
  75967. /**
  75968. * The scale of the bloom, lower value will provide better performance.
  75969. */
  75970. set: function (value) {
  75971. if (this._bloomScale === value) {
  75972. return;
  75973. }
  75974. this._bloomScale = value;
  75975. // recreate bloom and dispose old as this setting is not dynamic
  75976. this._rebuildBloom();
  75977. this._buildPipeline();
  75978. },
  75979. enumerable: true,
  75980. configurable: true
  75981. });
  75982. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75983. get: function () {
  75984. return this._bloomEnabled;
  75985. },
  75986. /**
  75987. * Enable or disable the bloom from the pipeline
  75988. */
  75989. set: function (enabled) {
  75990. if (this._bloomEnabled === enabled) {
  75991. return;
  75992. }
  75993. this._bloomEnabled = enabled;
  75994. this._buildPipeline();
  75995. },
  75996. enumerable: true,
  75997. configurable: true
  75998. });
  75999. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76000. // recreate bloom and dispose old as this setting is not dynamic
  76001. var oldBloom = this.bloom;
  76002. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76003. this.bloom.threshold = oldBloom.threshold;
  76004. for (var i = 0; i < this._cameras.length; i++) {
  76005. oldBloom.disposeEffects(this._cameras[i]);
  76006. }
  76007. };
  76008. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76009. /**
  76010. * If the depth of field is enabled.
  76011. */
  76012. get: function () {
  76013. return this._depthOfFieldEnabled;
  76014. },
  76015. set: function (enabled) {
  76016. if (this._depthOfFieldEnabled === enabled) {
  76017. return;
  76018. }
  76019. this._depthOfFieldEnabled = enabled;
  76020. this._buildPipeline();
  76021. },
  76022. enumerable: true,
  76023. configurable: true
  76024. });
  76025. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76026. /**
  76027. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76028. */
  76029. get: function () {
  76030. return this._depthOfFieldBlurLevel;
  76031. },
  76032. set: function (value) {
  76033. if (this._depthOfFieldBlurLevel === value) {
  76034. return;
  76035. }
  76036. this._depthOfFieldBlurLevel = value;
  76037. // recreate dof and dispose old as this setting is not dynamic
  76038. var oldDof = this.depthOfField;
  76039. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76040. this.depthOfField.focalLength = oldDof.focalLength;
  76041. this.depthOfField.focusDistance = oldDof.focusDistance;
  76042. this.depthOfField.fStop = oldDof.fStop;
  76043. this.depthOfField.lensSize = oldDof.lensSize;
  76044. for (var i = 0; i < this._cameras.length; i++) {
  76045. oldDof.disposeEffects(this._cameras[i]);
  76046. }
  76047. this._buildPipeline();
  76048. },
  76049. enumerable: true,
  76050. configurable: true
  76051. });
  76052. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76053. get: function () {
  76054. return this._fxaaEnabled;
  76055. },
  76056. /**
  76057. * If the anti aliasing is enabled.
  76058. */
  76059. set: function (enabled) {
  76060. if (this._fxaaEnabled === enabled) {
  76061. return;
  76062. }
  76063. this._fxaaEnabled = enabled;
  76064. this._buildPipeline();
  76065. },
  76066. enumerable: true,
  76067. configurable: true
  76068. });
  76069. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76070. get: function () {
  76071. return this._samples;
  76072. },
  76073. /**
  76074. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76075. */
  76076. set: function (sampleCount) {
  76077. if (this._samples === sampleCount) {
  76078. return;
  76079. }
  76080. this._samples = sampleCount;
  76081. this._buildPipeline();
  76082. },
  76083. enumerable: true,
  76084. configurable: true
  76085. });
  76086. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76087. get: function () {
  76088. return this._imageProcessingEnabled;
  76089. },
  76090. /**
  76091. * If image processing is enabled.
  76092. */
  76093. set: function (enabled) {
  76094. if (this._imageProcessingEnabled === enabled) {
  76095. return;
  76096. }
  76097. this._imageProcessingEnabled = enabled;
  76098. this._buildPipeline();
  76099. },
  76100. enumerable: true,
  76101. configurable: true
  76102. });
  76103. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76104. get: function () {
  76105. return this._glowLayer == null;
  76106. },
  76107. /**
  76108. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76109. */
  76110. set: function (enabled) {
  76111. if (enabled && !this._glowLayer) {
  76112. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76113. }
  76114. else if (!enabled && this._glowLayer) {
  76115. this._glowLayer.dispose();
  76116. this._glowLayer = null;
  76117. }
  76118. },
  76119. enumerable: true,
  76120. configurable: true
  76121. });
  76122. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76123. get: function () {
  76124. return this._chromaticAberrationEnabled;
  76125. },
  76126. /**
  76127. * Enable or disable the chromaticAberration process from the pipeline
  76128. */
  76129. set: function (enabled) {
  76130. if (this._chromaticAberrationEnabled === enabled) {
  76131. return;
  76132. }
  76133. this._chromaticAberrationEnabled = enabled;
  76134. this._buildPipeline();
  76135. },
  76136. enumerable: true,
  76137. configurable: true
  76138. });
  76139. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76140. get: function () {
  76141. return this._grainEnabled;
  76142. },
  76143. /**
  76144. * Enable or disable the grain process from the pipeline
  76145. */
  76146. set: function (enabled) {
  76147. if (this._grainEnabled === enabled) {
  76148. return;
  76149. }
  76150. this._grainEnabled = enabled;
  76151. this._buildPipeline();
  76152. },
  76153. enumerable: true,
  76154. configurable: true
  76155. });
  76156. /**
  76157. * Force the compilation of the entire pipeline.
  76158. */
  76159. DefaultRenderingPipeline.prototype.prepare = function () {
  76160. var previousState = this._buildAllowed;
  76161. this._buildAllowed = true;
  76162. this._buildPipeline();
  76163. this._buildAllowed = previousState;
  76164. };
  76165. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76166. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76167. if (this._hasCleared) {
  76168. postProcess.autoClear = false;
  76169. }
  76170. else {
  76171. postProcess.autoClear = true;
  76172. this._scene.autoClear = false;
  76173. this._hasCleared = true;
  76174. }
  76175. if (!skipTextureSharing) {
  76176. if (this._prevPrevPostProcess) {
  76177. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76178. }
  76179. else {
  76180. postProcess.useOwnOutput();
  76181. }
  76182. if (this._prevPostProcess) {
  76183. this._prevPrevPostProcess = this._prevPostProcess;
  76184. }
  76185. this._prevPostProcess = postProcess;
  76186. }
  76187. };
  76188. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76189. var _this = this;
  76190. if (!this._buildAllowed) {
  76191. return;
  76192. }
  76193. this._scene.autoClear = true;
  76194. var engine = this._scene.getEngine();
  76195. this._disposePostProcesses();
  76196. if (this._cameras !== null) {
  76197. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76198. // get back cameras to be used to reattach pipeline
  76199. this._cameras = this._originalCameras.slice();
  76200. }
  76201. this._reset();
  76202. this._prevPostProcess = null;
  76203. this._prevPrevPostProcess = null;
  76204. this._hasCleared = false;
  76205. if (this.depthOfFieldEnabled) {
  76206. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76207. this.depthOfField.depthTexture = depthTexture;
  76208. if (!this.depthOfField._isReady()) {
  76209. this.depthOfField._updateEffects();
  76210. }
  76211. this.addEffect(this.depthOfField);
  76212. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76213. }
  76214. if (this.bloomEnabled) {
  76215. if (!this.bloom._isReady()) {
  76216. this.bloom._updateEffects();
  76217. }
  76218. this.addEffect(this.bloom);
  76219. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76220. }
  76221. if (this._imageProcessingEnabled) {
  76222. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76223. if (this._hdr) {
  76224. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76225. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76226. }
  76227. else {
  76228. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76229. }
  76230. }
  76231. if (this.sharpenEnabled) {
  76232. if (!this.sharpen.isReady()) {
  76233. this.sharpen.updateEffect();
  76234. }
  76235. this.addEffect(this._sharpenEffect);
  76236. this._setAutoClearAndTextureSharing(this.sharpen);
  76237. }
  76238. if (this.grainEnabled) {
  76239. if (!this.grain.isReady()) {
  76240. this.grain.updateEffect();
  76241. }
  76242. this.addEffect(this._grainEffect);
  76243. this._setAutoClearAndTextureSharing(this.grain);
  76244. }
  76245. if (this.chromaticAberrationEnabled) {
  76246. if (!this.chromaticAberration.isReady()) {
  76247. this.chromaticAberration.updateEffect();
  76248. }
  76249. this.addEffect(this._chromaticAberrationEffect);
  76250. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76251. }
  76252. if (this.fxaaEnabled) {
  76253. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76254. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76255. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76256. }
  76257. if (this._cameras !== null) {
  76258. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76259. }
  76260. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76261. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76262. }
  76263. };
  76264. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76265. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76266. for (var i = 0; i < this._cameras.length; i++) {
  76267. var camera = this._cameras[i];
  76268. if (this.imageProcessing) {
  76269. this.imageProcessing.dispose(camera);
  76270. }
  76271. if (this.fxaa) {
  76272. this.fxaa.dispose(camera);
  76273. }
  76274. // These are created in the constructor and should not be disposed on every pipeline change
  76275. if (disposeNonRecreated) {
  76276. if (this.sharpen) {
  76277. this.sharpen.dispose(camera);
  76278. }
  76279. if (this.depthOfField) {
  76280. this.depthOfField.disposeEffects(camera);
  76281. }
  76282. if (this.bloom) {
  76283. this.bloom.disposeEffects(camera);
  76284. }
  76285. if (this.chromaticAberration) {
  76286. this.chromaticAberration.dispose(camera);
  76287. }
  76288. if (this.grain) {
  76289. this.grain.dispose(camera);
  76290. }
  76291. if (this._glowLayer) {
  76292. this._glowLayer.dispose();
  76293. }
  76294. }
  76295. }
  76296. this.imageProcessing = null;
  76297. this.fxaa = null;
  76298. if (disposeNonRecreated) {
  76299. this.sharpen = null;
  76300. this._sharpenEffect = null;
  76301. this.depthOfField = null;
  76302. this.bloom = null;
  76303. this.chromaticAberration = null;
  76304. this._chromaticAberrationEffect = null;
  76305. this.grain = null;
  76306. this._grainEffect = null;
  76307. this._glowLayer = null;
  76308. }
  76309. };
  76310. /**
  76311. * Dispose of the pipeline and stop all post processes
  76312. */
  76313. DefaultRenderingPipeline.prototype.dispose = function () {
  76314. this._disposePostProcesses(true);
  76315. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76316. this._scene.autoClear = true;
  76317. if (this._resizeObserver) {
  76318. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76319. this._resizeObserver = null;
  76320. }
  76321. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76322. _super.prototype.dispose.call(this);
  76323. };
  76324. /**
  76325. * Serialize the rendering pipeline (Used when exporting)
  76326. * @returns the serialized object
  76327. */
  76328. DefaultRenderingPipeline.prototype.serialize = function () {
  76329. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76330. serializationObject.customType = "DefaultRenderingPipeline";
  76331. return serializationObject;
  76332. };
  76333. /**
  76334. * Parse the serialized pipeline
  76335. * @param source Source pipeline.
  76336. * @param scene The scene to load the pipeline to.
  76337. * @param rootUrl The URL of the serialized pipeline.
  76338. * @returns An instantiated pipeline from the serialized object.
  76339. */
  76340. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76341. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76342. };
  76343. __decorate([
  76344. BABYLON.serialize()
  76345. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76346. __decorate([
  76347. BABYLON.serialize()
  76348. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76349. __decorate([
  76350. BABYLON.serialize()
  76351. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76352. __decorate([
  76353. BABYLON.serialize()
  76354. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76355. __decorate([
  76356. BABYLON.serialize()
  76357. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76358. __decorate([
  76359. BABYLON.serialize()
  76360. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76361. __decorate([
  76362. BABYLON.serialize()
  76363. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76364. __decorate([
  76365. BABYLON.serialize()
  76366. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76367. __decorate([
  76368. BABYLON.serialize()
  76369. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76370. __decorate([
  76371. BABYLON.serialize()
  76372. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76373. __decorate([
  76374. BABYLON.serialize()
  76375. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76376. __decorate([
  76377. BABYLON.serialize()
  76378. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76379. __decorate([
  76380. BABYLON.serialize()
  76381. ], DefaultRenderingPipeline.prototype, "samples", null);
  76382. __decorate([
  76383. BABYLON.serialize()
  76384. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76385. __decorate([
  76386. BABYLON.serialize()
  76387. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76388. __decorate([
  76389. BABYLON.serialize()
  76390. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76391. __decorate([
  76392. BABYLON.serialize()
  76393. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76394. return DefaultRenderingPipeline;
  76395. }(BABYLON.PostProcessRenderPipeline));
  76396. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76397. })(BABYLON || (BABYLON = {}));
  76398. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76399. var BABYLON;
  76400. (function (BABYLON) {
  76401. /**
  76402. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76403. */
  76404. var GeometryBufferRenderer = /** @class */ (function () {
  76405. /**
  76406. * Creates a new G Buffer for the scene
  76407. * @param scene The scene the buffer belongs to
  76408. * @param ratio How big is the buffer related to the main canvas.
  76409. */
  76410. function GeometryBufferRenderer(scene, ratio) {
  76411. if (ratio === void 0) { ratio = 1; }
  76412. this._enablePosition = false;
  76413. this._scene = scene;
  76414. this._ratio = ratio;
  76415. // Render target
  76416. this._createRenderTargets();
  76417. }
  76418. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76419. /**
  76420. * Set the render list (meshes to be rendered) used in the G buffer.
  76421. */
  76422. set: function (meshes) {
  76423. this._multiRenderTarget.renderList = meshes;
  76424. },
  76425. enumerable: true,
  76426. configurable: true
  76427. });
  76428. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76429. /**
  76430. * Gets wether or not G buffer are supported by the running hardware.
  76431. * This requires draw buffer supports
  76432. */
  76433. get: function () {
  76434. return this._multiRenderTarget.isSupported;
  76435. },
  76436. enumerable: true,
  76437. configurable: true
  76438. });
  76439. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76440. /**
  76441. * Gets wether or not position are enabled for the G buffer.
  76442. */
  76443. get: function () {
  76444. return this._enablePosition;
  76445. },
  76446. /**
  76447. * Sets wether or not position are enabled for the G buffer.
  76448. */
  76449. set: function (enable) {
  76450. this._enablePosition = enable;
  76451. this.dispose();
  76452. this._createRenderTargets();
  76453. },
  76454. enumerable: true,
  76455. configurable: true
  76456. });
  76457. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76458. /**
  76459. * Gets the scene associated with the buffer.
  76460. */
  76461. get: function () {
  76462. return this._scene;
  76463. },
  76464. enumerable: true,
  76465. configurable: true
  76466. });
  76467. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76468. /**
  76469. * Gets the ratio used by the buffer during its creation.
  76470. * How big is the buffer related to the main canvas.
  76471. */
  76472. get: function () {
  76473. return this._ratio;
  76474. },
  76475. enumerable: true,
  76476. configurable: true
  76477. });
  76478. /**
  76479. * Checks wether everything is ready to render a submesh to the G buffer.
  76480. * @param subMesh the submesh to check readiness for
  76481. * @param useInstances is the mesh drawn using instance or not
  76482. * @returns true if ready otherwise false
  76483. */
  76484. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76485. var material = subMesh.getMaterial();
  76486. if (material && material.disableDepthWrite) {
  76487. return false;
  76488. }
  76489. var defines = [];
  76490. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76491. var mesh = subMesh.getMesh();
  76492. // Alpha test
  76493. if (material && material.needAlphaTesting()) {
  76494. defines.push("#define ALPHATEST");
  76495. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76496. attribs.push(BABYLON.VertexBuffer.UVKind);
  76497. defines.push("#define UV1");
  76498. }
  76499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76500. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76501. defines.push("#define UV2");
  76502. }
  76503. }
  76504. // Buffers
  76505. if (this._enablePosition) {
  76506. defines.push("#define POSITION");
  76507. }
  76508. // Bones
  76509. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76510. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76511. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76512. if (mesh.numBoneInfluencers > 4) {
  76513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76515. }
  76516. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76517. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76518. }
  76519. else {
  76520. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76521. }
  76522. // Instances
  76523. if (useInstances) {
  76524. defines.push("#define INSTANCES");
  76525. attribs.push("world0");
  76526. attribs.push("world1");
  76527. attribs.push("world2");
  76528. attribs.push("world3");
  76529. }
  76530. // Get correct effect
  76531. var join = defines.join("\n");
  76532. if (this._cachedDefines !== join) {
  76533. this._cachedDefines = join;
  76534. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76535. }
  76536. return this._effect.isReady();
  76537. };
  76538. /**
  76539. * Gets the current underlying G Buffer.
  76540. * @returns the buffer
  76541. */
  76542. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76543. return this._multiRenderTarget;
  76544. };
  76545. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76546. /**
  76547. * Gets the number of samples used to render the buffer (anti aliasing).
  76548. */
  76549. get: function () {
  76550. return this._multiRenderTarget.samples;
  76551. },
  76552. /**
  76553. * Sets the number of samples used to render the buffer (anti aliasing).
  76554. */
  76555. set: function (value) {
  76556. this._multiRenderTarget.samples = value;
  76557. },
  76558. enumerable: true,
  76559. configurable: true
  76560. });
  76561. /**
  76562. * Disposes the renderer and frees up associated resources.
  76563. */
  76564. GeometryBufferRenderer.prototype.dispose = function () {
  76565. this.getGBuffer().dispose();
  76566. };
  76567. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76568. var _this = this;
  76569. var engine = this._scene.getEngine();
  76570. var count = this._enablePosition ? 3 : 2;
  76571. 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 });
  76572. if (!this.isSupported) {
  76573. return;
  76574. }
  76575. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76576. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76577. this._multiRenderTarget.refreshRate = 1;
  76578. this._multiRenderTarget.renderParticles = false;
  76579. this._multiRenderTarget.renderList = null;
  76580. // set default depth value to 1.0 (far away)
  76581. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76582. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76583. });
  76584. // Custom render function
  76585. var renderSubMesh = function (subMesh) {
  76586. var mesh = subMesh.getRenderingMesh();
  76587. var scene = _this._scene;
  76588. var engine = scene.getEngine();
  76589. var material = subMesh.getMaterial();
  76590. if (!material) {
  76591. return;
  76592. }
  76593. // Culling
  76594. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76595. // Managing instances
  76596. var batch = mesh._getInstancesRenderList(subMesh._id);
  76597. if (batch.mustReturn) {
  76598. return;
  76599. }
  76600. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76601. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76602. engine.enableEffect(_this._effect);
  76603. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76604. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76605. _this._effect.setMatrix("view", scene.getViewMatrix());
  76606. // Alpha test
  76607. if (material && material.needAlphaTesting()) {
  76608. var alphaTexture = material.getAlphaTestTexture();
  76609. if (alphaTexture) {
  76610. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76611. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76612. }
  76613. }
  76614. // Bones
  76615. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76616. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76617. }
  76618. // Draw
  76619. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76620. }
  76621. };
  76622. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76623. var index;
  76624. if (depthOnlySubMeshes.length) {
  76625. engine.setColorWrite(false);
  76626. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76627. renderSubMesh(depthOnlySubMeshes.data[index]);
  76628. }
  76629. engine.setColorWrite(true);
  76630. }
  76631. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76632. renderSubMesh(opaqueSubMeshes.data[index]);
  76633. }
  76634. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76635. renderSubMesh(alphaTestSubMeshes.data[index]);
  76636. }
  76637. };
  76638. };
  76639. return GeometryBufferRenderer;
  76640. }());
  76641. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76642. })(BABYLON || (BABYLON = {}));
  76643. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76644. var BABYLON;
  76645. (function (BABYLON) {
  76646. /**
  76647. * This groups together the common properties used for image processing either in direct forward pass
  76648. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76649. * or not.
  76650. */
  76651. var ImageProcessingConfiguration = /** @class */ (function () {
  76652. function ImageProcessingConfiguration() {
  76653. /**
  76654. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76655. */
  76656. this.colorCurves = new BABYLON.ColorCurves();
  76657. this._colorCurvesEnabled = false;
  76658. this._colorGradingEnabled = false;
  76659. this._colorGradingWithGreenDepth = true;
  76660. this._colorGradingBGR = true;
  76661. this._exposure = 1.0;
  76662. this._toneMappingEnabled = false;
  76663. this._contrast = 1.0;
  76664. /**
  76665. * Vignette stretch size.
  76666. */
  76667. this.vignetteStretch = 0;
  76668. /**
  76669. * Vignette centre X Offset.
  76670. */
  76671. this.vignetteCentreX = 0;
  76672. /**
  76673. * Vignette centre Y Offset.
  76674. */
  76675. this.vignetteCentreY = 0;
  76676. /**
  76677. * Vignette weight or intensity of the vignette effect.
  76678. */
  76679. this.vignetteWeight = 1.5;
  76680. /**
  76681. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76682. * if vignetteEnabled is set to true.
  76683. */
  76684. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76685. /**
  76686. * Camera field of view used by the Vignette effect.
  76687. */
  76688. this.vignetteCameraFov = 0.5;
  76689. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  76690. this._vignetteEnabled = false;
  76691. this._applyByPostProcess = false;
  76692. this._isEnabled = true;
  76693. /**
  76694. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  76695. */
  76696. this.onUpdateParameters = new BABYLON.Observable();
  76697. }
  76698. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  76699. /**
  76700. * Gets wether the color curves effect is enabled.
  76701. */
  76702. get: function () {
  76703. return this._colorCurvesEnabled;
  76704. },
  76705. /**
  76706. * Sets wether the color curves effect is enabled.
  76707. */
  76708. set: function (value) {
  76709. if (this._colorCurvesEnabled === value) {
  76710. return;
  76711. }
  76712. this._colorCurvesEnabled = value;
  76713. this._updateParameters();
  76714. },
  76715. enumerable: true,
  76716. configurable: true
  76717. });
  76718. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  76719. /**
  76720. * Gets wether the color grading effect is enabled.
  76721. */
  76722. get: function () {
  76723. return this._colorGradingEnabled;
  76724. },
  76725. /**
  76726. * Sets wether the color grading effect is enabled.
  76727. */
  76728. set: function (value) {
  76729. if (this._colorGradingEnabled === value) {
  76730. return;
  76731. }
  76732. this._colorGradingEnabled = value;
  76733. this._updateParameters();
  76734. },
  76735. enumerable: true,
  76736. configurable: true
  76737. });
  76738. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  76739. /**
  76740. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  76741. */
  76742. get: function () {
  76743. return this._colorGradingWithGreenDepth;
  76744. },
  76745. /**
  76746. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  76747. */
  76748. set: function (value) {
  76749. if (this._colorGradingWithGreenDepth === value) {
  76750. return;
  76751. }
  76752. this._colorGradingWithGreenDepth = value;
  76753. this._updateParameters();
  76754. },
  76755. enumerable: true,
  76756. configurable: true
  76757. });
  76758. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  76759. /**
  76760. * Gets wether the color grading texture contains BGR values.
  76761. */
  76762. get: function () {
  76763. return this._colorGradingBGR;
  76764. },
  76765. /**
  76766. * Sets wether the color grading texture contains BGR values.
  76767. */
  76768. set: function (value) {
  76769. if (this._colorGradingBGR === value) {
  76770. return;
  76771. }
  76772. this._colorGradingBGR = value;
  76773. this._updateParameters();
  76774. },
  76775. enumerable: true,
  76776. configurable: true
  76777. });
  76778. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  76779. /**
  76780. * Gets the Exposure used in the effect.
  76781. */
  76782. get: function () {
  76783. return this._exposure;
  76784. },
  76785. /**
  76786. * Sets the Exposure used in the effect.
  76787. */
  76788. set: function (value) {
  76789. if (this._exposure === value) {
  76790. return;
  76791. }
  76792. this._exposure = value;
  76793. this._updateParameters();
  76794. },
  76795. enumerable: true,
  76796. configurable: true
  76797. });
  76798. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  76799. /**
  76800. * Gets wether the tone mapping effect is enabled.
  76801. */
  76802. get: function () {
  76803. return this._toneMappingEnabled;
  76804. },
  76805. /**
  76806. * Sets wether the tone mapping effect is enabled.
  76807. */
  76808. set: function (value) {
  76809. if (this._toneMappingEnabled === value) {
  76810. return;
  76811. }
  76812. this._toneMappingEnabled = value;
  76813. this._updateParameters();
  76814. },
  76815. enumerable: true,
  76816. configurable: true
  76817. });
  76818. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  76819. /**
  76820. * Gets the contrast used in the effect.
  76821. */
  76822. get: function () {
  76823. return this._contrast;
  76824. },
  76825. /**
  76826. * Sets the contrast used in the effect.
  76827. */
  76828. set: function (value) {
  76829. if (this._contrast === value) {
  76830. return;
  76831. }
  76832. this._contrast = value;
  76833. this._updateParameters();
  76834. },
  76835. enumerable: true,
  76836. configurable: true
  76837. });
  76838. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  76839. /**
  76840. * Gets the vignette blend mode allowing different kind of effect.
  76841. */
  76842. get: function () {
  76843. return this._vignetteBlendMode;
  76844. },
  76845. /**
  76846. * Sets the vignette blend mode allowing different kind of effect.
  76847. */
  76848. set: function (value) {
  76849. if (this._vignetteBlendMode === value) {
  76850. return;
  76851. }
  76852. this._vignetteBlendMode = value;
  76853. this._updateParameters();
  76854. },
  76855. enumerable: true,
  76856. configurable: true
  76857. });
  76858. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  76859. /**
  76860. * Gets wether the vignette effect is enabled.
  76861. */
  76862. get: function () {
  76863. return this._vignetteEnabled;
  76864. },
  76865. /**
  76866. * Sets wether the vignette effect is enabled.
  76867. */
  76868. set: function (value) {
  76869. if (this._vignetteEnabled === value) {
  76870. return;
  76871. }
  76872. this._vignetteEnabled = value;
  76873. this._updateParameters();
  76874. },
  76875. enumerable: true,
  76876. configurable: true
  76877. });
  76878. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  76879. /**
  76880. * Gets wether the image processing is applied through a post process or not.
  76881. */
  76882. get: function () {
  76883. return this._applyByPostProcess;
  76884. },
  76885. /**
  76886. * Sets wether the image processing is applied through a post process or not.
  76887. */
  76888. set: function (value) {
  76889. if (this._applyByPostProcess === value) {
  76890. return;
  76891. }
  76892. this._applyByPostProcess = value;
  76893. this._updateParameters();
  76894. },
  76895. enumerable: true,
  76896. configurable: true
  76897. });
  76898. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  76899. /**
  76900. * Gets wether the image processing is enabled or not.
  76901. */
  76902. get: function () {
  76903. return this._isEnabled;
  76904. },
  76905. /**
  76906. * Sets wether the image processing is enabled or not.
  76907. */
  76908. set: function (value) {
  76909. if (this._isEnabled === value) {
  76910. return;
  76911. }
  76912. this._isEnabled = value;
  76913. this._updateParameters();
  76914. },
  76915. enumerable: true,
  76916. configurable: true
  76917. });
  76918. /**
  76919. * Method called each time the image processing information changes requires to recompile the effect.
  76920. */
  76921. ImageProcessingConfiguration.prototype._updateParameters = function () {
  76922. this.onUpdateParameters.notifyObservers(this);
  76923. };
  76924. ImageProcessingConfiguration.prototype.getClassName = function () {
  76925. return "ImageProcessingConfiguration";
  76926. };
  76927. /**
  76928. * Prepare the list of uniforms associated with the Image Processing effects.
  76929. * @param uniformsList The list of uniforms used in the effect
  76930. * @param defines the list of defines currently in use
  76931. */
  76932. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  76933. if (defines.EXPOSURE) {
  76934. uniforms.push("exposureLinear");
  76935. }
  76936. if (defines.CONTRAST) {
  76937. uniforms.push("contrast");
  76938. }
  76939. if (defines.COLORGRADING) {
  76940. uniforms.push("colorTransformSettings");
  76941. }
  76942. if (defines.VIGNETTE) {
  76943. uniforms.push("vInverseScreenSize");
  76944. uniforms.push("vignetteSettings1");
  76945. uniforms.push("vignetteSettings2");
  76946. }
  76947. if (defines.COLORCURVES) {
  76948. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  76949. }
  76950. };
  76951. /**
  76952. * Prepare the list of samplers associated with the Image Processing effects.
  76953. * @param uniformsList The list of uniforms used in the effect
  76954. * @param defines the list of defines currently in use
  76955. */
  76956. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  76957. if (defines.COLORGRADING) {
  76958. samplersList.push("txColorTransform");
  76959. }
  76960. };
  76961. /**
  76962. * Prepare the list of defines associated to the shader.
  76963. * @param defines the list of defines to complete
  76964. */
  76965. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  76966. if (forPostProcess === void 0) { forPostProcess = false; }
  76967. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  76968. defines.VIGNETTE = false;
  76969. defines.TONEMAPPING = false;
  76970. defines.CONTRAST = false;
  76971. defines.EXPOSURE = false;
  76972. defines.COLORCURVES = false;
  76973. defines.COLORGRADING = false;
  76974. defines.COLORGRADING3D = false;
  76975. defines.IMAGEPROCESSING = false;
  76976. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  76977. return;
  76978. }
  76979. defines.VIGNETTE = this.vignetteEnabled;
  76980. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  76981. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  76982. defines.TONEMAPPING = this.toneMappingEnabled;
  76983. defines.CONTRAST = (this.contrast !== 1.0);
  76984. defines.EXPOSURE = (this.exposure !== 1.0);
  76985. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  76986. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  76987. if (defines.COLORGRADING) {
  76988. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  76989. }
  76990. else {
  76991. defines.COLORGRADING3D = false;
  76992. }
  76993. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  76994. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  76995. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  76996. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  76997. };
  76998. /**
  76999. * Returns true if all the image processing information are ready.
  77000. */
  77001. ImageProcessingConfiguration.prototype.isReady = function () {
  77002. // Color Grading texure can not be none blocking.
  77003. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77004. };
  77005. /**
  77006. * Binds the image processing to the shader.
  77007. * @param effect The effect to bind to
  77008. */
  77009. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77010. if (aspectRatio === void 0) { aspectRatio = 1; }
  77011. // Color Curves
  77012. if (this._colorCurvesEnabled && this.colorCurves) {
  77013. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77014. }
  77015. // Vignette
  77016. if (this._vignetteEnabled) {
  77017. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77018. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77019. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77020. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77021. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77022. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77023. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77024. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77025. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77026. var vignettePower = -2.0 * this.vignetteWeight;
  77027. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77028. }
  77029. // Exposure
  77030. effect.setFloat("exposureLinear", this.exposure);
  77031. // Contrast
  77032. effect.setFloat("contrast", this.contrast);
  77033. // Color transform settings
  77034. if (this.colorGradingTexture) {
  77035. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77036. var textureSize = this.colorGradingTexture.getSize().height;
  77037. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77038. 0.5 / textureSize, // textureOffset
  77039. textureSize, // textureSize
  77040. this.colorGradingTexture.level // weight
  77041. );
  77042. }
  77043. };
  77044. /**
  77045. * Clones the current image processing instance.
  77046. * @return The cloned image processing
  77047. */
  77048. ImageProcessingConfiguration.prototype.clone = function () {
  77049. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77050. };
  77051. /**
  77052. * Serializes the current image processing instance to a json representation.
  77053. * @return a JSON representation
  77054. */
  77055. ImageProcessingConfiguration.prototype.serialize = function () {
  77056. return BABYLON.SerializationHelper.Serialize(this);
  77057. };
  77058. /**
  77059. * Parses the image processing from a json representation.
  77060. * @param source the JSON source to parse
  77061. * @return The parsed image processing
  77062. */
  77063. ImageProcessingConfiguration.Parse = function (source) {
  77064. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77065. };
  77066. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77067. /**
  77068. * Used to apply the vignette as a mix with the pixel color.
  77069. */
  77070. get: function () {
  77071. return this._VIGNETTEMODE_MULTIPLY;
  77072. },
  77073. enumerable: true,
  77074. configurable: true
  77075. });
  77076. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77077. /**
  77078. * Used to apply the vignette as a replacement of the pixel color.
  77079. */
  77080. get: function () {
  77081. return this._VIGNETTEMODE_OPAQUE;
  77082. },
  77083. enumerable: true,
  77084. configurable: true
  77085. });
  77086. // Static constants associated to the image processing.
  77087. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77088. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77089. __decorate([
  77090. BABYLON.serializeAsColorCurves()
  77091. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77092. __decorate([
  77093. BABYLON.serialize()
  77094. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77095. __decorate([
  77096. BABYLON.serializeAsTexture()
  77097. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77098. __decorate([
  77099. BABYLON.serialize()
  77100. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77101. __decorate([
  77102. BABYLON.serialize()
  77103. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77104. __decorate([
  77105. BABYLON.serialize()
  77106. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77107. __decorate([
  77108. BABYLON.serialize()
  77109. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77110. __decorate([
  77111. BABYLON.serialize()
  77112. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77113. __decorate([
  77114. BABYLON.serialize()
  77115. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77116. __decorate([
  77117. BABYLON.serialize()
  77118. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77119. __decorate([
  77120. BABYLON.serialize()
  77121. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77122. __decorate([
  77123. BABYLON.serialize()
  77124. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77125. __decorate([
  77126. BABYLON.serialize()
  77127. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77128. __decorate([
  77129. BABYLON.serializeAsColor4()
  77130. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77131. __decorate([
  77132. BABYLON.serialize()
  77133. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77134. __decorate([
  77135. BABYLON.serialize()
  77136. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77137. __decorate([
  77138. BABYLON.serialize()
  77139. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77140. __decorate([
  77141. BABYLON.serialize()
  77142. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77143. __decorate([
  77144. BABYLON.serialize()
  77145. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77146. return ImageProcessingConfiguration;
  77147. }());
  77148. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77149. })(BABYLON || (BABYLON = {}));
  77150. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77151. var BABYLON;
  77152. (function (BABYLON) {
  77153. /**
  77154. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77155. * It can help converting any input color in a desired output one. This can then be used to create effects
  77156. * from sepia, black and white to sixties or futuristic rendering...
  77157. *
  77158. * The only supported format is currently 3dl.
  77159. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77160. */
  77161. var ColorGradingTexture = /** @class */ (function (_super) {
  77162. __extends(ColorGradingTexture, _super);
  77163. /**
  77164. * Instantiates a ColorGradingTexture from the following parameters.
  77165. *
  77166. * @param url The location of the color gradind data (currently only supporting 3dl)
  77167. * @param scene The scene the texture will be used in
  77168. */
  77169. function ColorGradingTexture(url, scene) {
  77170. var _this = _super.call(this, scene) || this;
  77171. if (!url) {
  77172. return _this;
  77173. }
  77174. _this._engine = scene.getEngine();
  77175. _this._textureMatrix = BABYLON.Matrix.Identity();
  77176. _this.name = url;
  77177. _this.url = url;
  77178. _this.hasAlpha = false;
  77179. _this.isCube = false;
  77180. _this.is3D = _this._engine.webGLVersion > 1;
  77181. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77182. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77183. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77184. _this.anisotropicFilteringLevel = 1;
  77185. _this._texture = _this._getFromCache(url, true);
  77186. if (!_this._texture) {
  77187. if (!scene.useDelayedTextureLoading) {
  77188. _this.loadTexture();
  77189. }
  77190. else {
  77191. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77192. }
  77193. }
  77194. return _this;
  77195. }
  77196. /**
  77197. * Returns the texture matrix used in most of the material.
  77198. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77199. */
  77200. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77201. return this._textureMatrix;
  77202. };
  77203. /**
  77204. * Occurs when the file being loaded is a .3dl LUT file.
  77205. */
  77206. ColorGradingTexture.prototype.load3dlTexture = function () {
  77207. var engine = this._engine;
  77208. var texture;
  77209. if (engine.webGLVersion === 1) {
  77210. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77211. }
  77212. else {
  77213. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77214. }
  77215. this._texture = texture;
  77216. var callback = function (text) {
  77217. if (typeof text !== "string") {
  77218. return;
  77219. }
  77220. var data = null;
  77221. var tempData = null;
  77222. var line;
  77223. var lines = text.split('\n');
  77224. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77225. var maxColor = 0;
  77226. for (var i = 0; i < lines.length; i++) {
  77227. line = lines[i];
  77228. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77229. continue;
  77230. if (line.indexOf('#') === 0)
  77231. continue;
  77232. var words = line.split(" ");
  77233. if (size === 0) {
  77234. // Number of space + one
  77235. size = words.length;
  77236. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77237. tempData = new Float32Array(size * size * size * 4);
  77238. continue;
  77239. }
  77240. if (size != 0) {
  77241. var r = Math.max(parseInt(words[0]), 0);
  77242. var g = Math.max(parseInt(words[1]), 0);
  77243. var b = Math.max(parseInt(words[2]), 0);
  77244. maxColor = Math.max(r, maxColor);
  77245. maxColor = Math.max(g, maxColor);
  77246. maxColor = Math.max(b, maxColor);
  77247. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77248. if (tempData) {
  77249. tempData[pixelStorageIndex + 0] = r;
  77250. tempData[pixelStorageIndex + 1] = g;
  77251. tempData[pixelStorageIndex + 2] = b;
  77252. }
  77253. pixelIndexSlice++;
  77254. if (pixelIndexSlice % size == 0) {
  77255. pixelIndexH++;
  77256. pixelIndexSlice = 0;
  77257. if (pixelIndexH % size == 0) {
  77258. pixelIndexW++;
  77259. pixelIndexH = 0;
  77260. }
  77261. }
  77262. }
  77263. }
  77264. if (tempData && data) {
  77265. for (var i = 0; i < tempData.length; i++) {
  77266. if (i > 0 && (i + 1) % 4 === 0) {
  77267. data[i] = 255;
  77268. }
  77269. else {
  77270. var value = tempData[i];
  77271. data[i] = (value / maxColor * 255);
  77272. }
  77273. }
  77274. }
  77275. if (texture.is3D) {
  77276. texture.updateSize(size, size, size);
  77277. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77278. }
  77279. else {
  77280. texture.updateSize(size * size, size);
  77281. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77282. }
  77283. };
  77284. var scene = this.getScene();
  77285. if (scene) {
  77286. scene._loadFile(this.url, callback);
  77287. }
  77288. else {
  77289. this._engine._loadFile(this.url, callback);
  77290. }
  77291. return this._texture;
  77292. };
  77293. /**
  77294. * Starts the loading process of the texture.
  77295. */
  77296. ColorGradingTexture.prototype.loadTexture = function () {
  77297. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77298. this.load3dlTexture();
  77299. }
  77300. };
  77301. /**
  77302. * Clones the color gradind texture.
  77303. */
  77304. ColorGradingTexture.prototype.clone = function () {
  77305. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77306. // Base texture
  77307. newTexture.level = this.level;
  77308. return newTexture;
  77309. };
  77310. /**
  77311. * Called during delayed load for textures.
  77312. */
  77313. ColorGradingTexture.prototype.delayLoad = function () {
  77314. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77315. return;
  77316. }
  77317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77318. this._texture = this._getFromCache(this.url, true);
  77319. if (!this._texture) {
  77320. this.loadTexture();
  77321. }
  77322. };
  77323. /**
  77324. * Parses a color grading texture serialized by Babylon.
  77325. * @param parsedTexture The texture information being parsedTexture
  77326. * @param scene The scene to load the texture in
  77327. * @param rootUrl The root url of the data assets to load
  77328. * @return A color gradind texture
  77329. */
  77330. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77331. var texture = null;
  77332. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77333. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77334. texture.name = parsedTexture.name;
  77335. texture.level = parsedTexture.level;
  77336. }
  77337. return texture;
  77338. };
  77339. /**
  77340. * Serializes the LUT texture to json format.
  77341. */
  77342. ColorGradingTexture.prototype.serialize = function () {
  77343. if (!this.name) {
  77344. return null;
  77345. }
  77346. var serializationObject = {};
  77347. serializationObject.name = this.name;
  77348. serializationObject.level = this.level;
  77349. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77350. return serializationObject;
  77351. };
  77352. /**
  77353. * Empty line regex stored for GC.
  77354. */
  77355. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77356. return ColorGradingTexture;
  77357. }(BABYLON.BaseTexture));
  77358. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77359. })(BABYLON || (BABYLON = {}));
  77360. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77361. var BABYLON;
  77362. (function (BABYLON) {
  77363. /**
  77364. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77365. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77366. * 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;
  77367. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77368. */
  77369. var ColorCurves = /** @class */ (function () {
  77370. function ColorCurves() {
  77371. this._dirty = true;
  77372. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77373. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77374. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77375. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77376. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77377. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77378. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77379. this._globalHue = 30;
  77380. this._globalDensity = 0;
  77381. this._globalSaturation = 0;
  77382. this._globalExposure = 0;
  77383. this._highlightsHue = 30;
  77384. this._highlightsDensity = 0;
  77385. this._highlightsSaturation = 0;
  77386. this._highlightsExposure = 0;
  77387. this._midtonesHue = 30;
  77388. this._midtonesDensity = 0;
  77389. this._midtonesSaturation = 0;
  77390. this._midtonesExposure = 0;
  77391. this._shadowsHue = 30;
  77392. this._shadowsDensity = 0;
  77393. this._shadowsSaturation = 0;
  77394. this._shadowsExposure = 0;
  77395. }
  77396. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77397. /**
  77398. * Gets the global Hue value.
  77399. * 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).
  77400. */
  77401. get: function () {
  77402. return this._globalHue;
  77403. },
  77404. /**
  77405. * Sets the global Hue value.
  77406. * 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).
  77407. */
  77408. set: function (value) {
  77409. this._globalHue = value;
  77410. this._dirty = true;
  77411. },
  77412. enumerable: true,
  77413. configurable: true
  77414. });
  77415. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77416. /**
  77417. * Gets the global Density value.
  77418. * 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.
  77419. * Values less than zero provide a filter of opposite hue.
  77420. */
  77421. get: function () {
  77422. return this._globalDensity;
  77423. },
  77424. /**
  77425. * Sets the global Density value.
  77426. * 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.
  77427. * Values less than zero provide a filter of opposite hue.
  77428. */
  77429. set: function (value) {
  77430. this._globalDensity = value;
  77431. this._dirty = true;
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77437. /**
  77438. * Gets the global Saturation value.
  77439. * 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.
  77440. */
  77441. get: function () {
  77442. return this._globalSaturation;
  77443. },
  77444. /**
  77445. * Sets the global Saturation value.
  77446. * 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.
  77447. */
  77448. set: function (value) {
  77449. this._globalSaturation = value;
  77450. this._dirty = true;
  77451. },
  77452. enumerable: true,
  77453. configurable: true
  77454. });
  77455. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77456. /**
  77457. * Gets the global Exposure value.
  77458. * 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.
  77459. */
  77460. get: function () {
  77461. return this._globalExposure;
  77462. },
  77463. /**
  77464. * Sets the global Exposure value.
  77465. * 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.
  77466. */
  77467. set: function (value) {
  77468. this._globalExposure = value;
  77469. this._dirty = true;
  77470. },
  77471. enumerable: true,
  77472. configurable: true
  77473. });
  77474. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77475. /**
  77476. * Gets the highlights Hue value.
  77477. * 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).
  77478. */
  77479. get: function () {
  77480. return this._highlightsHue;
  77481. },
  77482. /**
  77483. * Sets the highlights Hue value.
  77484. * 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).
  77485. */
  77486. set: function (value) {
  77487. this._highlightsHue = value;
  77488. this._dirty = true;
  77489. },
  77490. enumerable: true,
  77491. configurable: true
  77492. });
  77493. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77494. /**
  77495. * Gets the highlights Density value.
  77496. * 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.
  77497. * Values less than zero provide a filter of opposite hue.
  77498. */
  77499. get: function () {
  77500. return this._highlightsDensity;
  77501. },
  77502. /**
  77503. * Sets the highlights Density value.
  77504. * 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.
  77505. * Values less than zero provide a filter of opposite hue.
  77506. */
  77507. set: function (value) {
  77508. this._highlightsDensity = value;
  77509. this._dirty = true;
  77510. },
  77511. enumerable: true,
  77512. configurable: true
  77513. });
  77514. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77515. /**
  77516. * Gets the highlights Saturation value.
  77517. * 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.
  77518. */
  77519. get: function () {
  77520. return this._highlightsSaturation;
  77521. },
  77522. /**
  77523. * Sets the highlights Saturation value.
  77524. * 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.
  77525. */
  77526. set: function (value) {
  77527. this._highlightsSaturation = value;
  77528. this._dirty = true;
  77529. },
  77530. enumerable: true,
  77531. configurable: true
  77532. });
  77533. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77534. /**
  77535. * Gets the highlights Exposure value.
  77536. * 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.
  77537. */
  77538. get: function () {
  77539. return this._highlightsExposure;
  77540. },
  77541. /**
  77542. * Sets the highlights Exposure value.
  77543. * 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.
  77544. */
  77545. set: function (value) {
  77546. this._highlightsExposure = value;
  77547. this._dirty = true;
  77548. },
  77549. enumerable: true,
  77550. configurable: true
  77551. });
  77552. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77553. /**
  77554. * Gets the midtones Hue value.
  77555. * 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).
  77556. */
  77557. get: function () {
  77558. return this._midtonesHue;
  77559. },
  77560. /**
  77561. * Sets the midtones Hue value.
  77562. * 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).
  77563. */
  77564. set: function (value) {
  77565. this._midtonesHue = value;
  77566. this._dirty = true;
  77567. },
  77568. enumerable: true,
  77569. configurable: true
  77570. });
  77571. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77572. /**
  77573. * Gets the midtones Density value.
  77574. * 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.
  77575. * Values less than zero provide a filter of opposite hue.
  77576. */
  77577. get: function () {
  77578. return this._midtonesDensity;
  77579. },
  77580. /**
  77581. * Sets the midtones Density value.
  77582. * 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.
  77583. * Values less than zero provide a filter of opposite hue.
  77584. */
  77585. set: function (value) {
  77586. this._midtonesDensity = value;
  77587. this._dirty = true;
  77588. },
  77589. enumerable: true,
  77590. configurable: true
  77591. });
  77592. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77593. /**
  77594. * Gets the midtones Saturation value.
  77595. * 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.
  77596. */
  77597. get: function () {
  77598. return this._midtonesSaturation;
  77599. },
  77600. /**
  77601. * Sets the midtones Saturation value.
  77602. * 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.
  77603. */
  77604. set: function (value) {
  77605. this._midtonesSaturation = value;
  77606. this._dirty = true;
  77607. },
  77608. enumerable: true,
  77609. configurable: true
  77610. });
  77611. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77612. /**
  77613. * Gets the midtones Exposure value.
  77614. * 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.
  77615. */
  77616. get: function () {
  77617. return this._midtonesExposure;
  77618. },
  77619. /**
  77620. * Sets the midtones Exposure value.
  77621. * 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.
  77622. */
  77623. set: function (value) {
  77624. this._midtonesExposure = value;
  77625. this._dirty = true;
  77626. },
  77627. enumerable: true,
  77628. configurable: true
  77629. });
  77630. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77631. /**
  77632. * Gets the shadows Hue value.
  77633. * 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).
  77634. */
  77635. get: function () {
  77636. return this._shadowsHue;
  77637. },
  77638. /**
  77639. * Sets the shadows Hue value.
  77640. * 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).
  77641. */
  77642. set: function (value) {
  77643. this._shadowsHue = value;
  77644. this._dirty = true;
  77645. },
  77646. enumerable: true,
  77647. configurable: true
  77648. });
  77649. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77650. /**
  77651. * Gets the shadows Density value.
  77652. * 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.
  77653. * Values less than zero provide a filter of opposite hue.
  77654. */
  77655. get: function () {
  77656. return this._shadowsDensity;
  77657. },
  77658. /**
  77659. * Sets the shadows Density value.
  77660. * 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.
  77661. * Values less than zero provide a filter of opposite hue.
  77662. */
  77663. set: function (value) {
  77664. this._shadowsDensity = value;
  77665. this._dirty = true;
  77666. },
  77667. enumerable: true,
  77668. configurable: true
  77669. });
  77670. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77671. /**
  77672. * Gets the shadows Saturation value.
  77673. * 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.
  77674. */
  77675. get: function () {
  77676. return this._shadowsSaturation;
  77677. },
  77678. /**
  77679. * Sets the shadows Saturation value.
  77680. * 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.
  77681. */
  77682. set: function (value) {
  77683. this._shadowsSaturation = value;
  77684. this._dirty = true;
  77685. },
  77686. enumerable: true,
  77687. configurable: true
  77688. });
  77689. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  77690. /**
  77691. * Gets the shadows Exposure value.
  77692. * 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.
  77693. */
  77694. get: function () {
  77695. return this._shadowsExposure;
  77696. },
  77697. /**
  77698. * Sets the shadows Exposure value.
  77699. * 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.
  77700. */
  77701. set: function (value) {
  77702. this._shadowsExposure = value;
  77703. this._dirty = true;
  77704. },
  77705. enumerable: true,
  77706. configurable: true
  77707. });
  77708. ColorCurves.prototype.getClassName = function () {
  77709. return "ColorCurves";
  77710. };
  77711. /**
  77712. * Binds the color curves to the shader.
  77713. * @param colorCurves The color curve to bind
  77714. * @param effect The effect to bind to
  77715. */
  77716. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  77717. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  77718. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  77719. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  77720. if (colorCurves._dirty) {
  77721. colorCurves._dirty = false;
  77722. // Fill in global info.
  77723. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  77724. // Compute highlights info.
  77725. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  77726. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  77727. // Compute midtones info.
  77728. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  77729. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  77730. // Compute shadows info.
  77731. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  77732. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  77733. // Compute deltas (neutral is midtones).
  77734. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  77735. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  77736. }
  77737. if (effect) {
  77738. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  77739. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  77740. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  77741. }
  77742. };
  77743. /**
  77744. * Prepare the list of uniforms associated with the ColorCurves effects.
  77745. * @param uniformsList The list of uniforms used in the effect
  77746. */
  77747. ColorCurves.PrepareUniforms = function (uniformsList) {
  77748. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  77749. };
  77750. /**
  77751. * Returns color grading data based on a hue, density, saturation and exposure value.
  77752. * @param filterHue The hue of the color filter.
  77753. * @param filterDensity The density of the color filter.
  77754. * @param saturation The saturation.
  77755. * @param exposure The exposure.
  77756. * @param result The result data container.
  77757. */
  77758. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  77759. if (hue == null) {
  77760. return;
  77761. }
  77762. hue = ColorCurves.clamp(hue, 0, 360);
  77763. density = ColorCurves.clamp(density, -100, 100);
  77764. saturation = ColorCurves.clamp(saturation, -100, 100);
  77765. exposure = ColorCurves.clamp(exposure, -100, 100);
  77766. // Remap the slider/config filter density with non-linear mapping and also scale by half
  77767. // so that the maximum filter density is only 50% control. This provides fine control
  77768. // for small values and reasonable range.
  77769. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  77770. density *= 0.5;
  77771. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  77772. if (density < 0) {
  77773. density *= -1;
  77774. hue = (hue + 180) % 360;
  77775. }
  77776. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  77777. result.scaleToRef(2, result);
  77778. result.a = 1 + 0.01 * saturation;
  77779. };
  77780. /**
  77781. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  77782. * @param value The input slider value in range [-100,100].
  77783. * @returns Adjusted value.
  77784. */
  77785. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  77786. value /= 100;
  77787. var x = Math.abs(value);
  77788. x = Math.pow(x, 2);
  77789. if (value < 0) {
  77790. x *= -1;
  77791. }
  77792. x *= 100;
  77793. return x;
  77794. };
  77795. /**
  77796. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  77797. * @param hue The hue (H) input.
  77798. * @param saturation The saturation (S) input.
  77799. * @param brightness The brightness (B) input.
  77800. * @result An RGBA color represented as Vector4.
  77801. */
  77802. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  77803. var h = ColorCurves.clamp(hue, 0, 360);
  77804. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  77805. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  77806. if (s === 0) {
  77807. result.r = v;
  77808. result.g = v;
  77809. result.b = v;
  77810. }
  77811. else {
  77812. // sector 0 to 5
  77813. h /= 60;
  77814. var i = Math.floor(h);
  77815. // fractional part of h
  77816. var f = h - i;
  77817. var p = v * (1 - s);
  77818. var q = v * (1 - s * f);
  77819. var t = v * (1 - s * (1 - f));
  77820. switch (i) {
  77821. case 0:
  77822. result.r = v;
  77823. result.g = t;
  77824. result.b = p;
  77825. break;
  77826. case 1:
  77827. result.r = q;
  77828. result.g = v;
  77829. result.b = p;
  77830. break;
  77831. case 2:
  77832. result.r = p;
  77833. result.g = v;
  77834. result.b = t;
  77835. break;
  77836. case 3:
  77837. result.r = p;
  77838. result.g = q;
  77839. result.b = v;
  77840. break;
  77841. case 4:
  77842. result.r = t;
  77843. result.g = p;
  77844. result.b = v;
  77845. break;
  77846. default: // case 5:
  77847. result.r = v;
  77848. result.g = p;
  77849. result.b = q;
  77850. break;
  77851. }
  77852. }
  77853. result.a = 1;
  77854. };
  77855. /**
  77856. * Returns a value clamped between min and max
  77857. * @param value The value to clamp
  77858. * @param min The minimum of value
  77859. * @param max The maximum of value
  77860. * @returns The clamped value.
  77861. */
  77862. ColorCurves.clamp = function (value, min, max) {
  77863. return Math.min(Math.max(value, min), max);
  77864. };
  77865. /**
  77866. * Clones the current color curve instance.
  77867. * @return The cloned curves
  77868. */
  77869. ColorCurves.prototype.clone = function () {
  77870. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  77871. };
  77872. /**
  77873. * Serializes the current color curve instance to a json representation.
  77874. * @return a JSON representation
  77875. */
  77876. ColorCurves.prototype.serialize = function () {
  77877. return BABYLON.SerializationHelper.Serialize(this);
  77878. };
  77879. /**
  77880. * Parses the color curve from a json representation.
  77881. * @param source the JSON source to parse
  77882. * @return The parsed curves
  77883. */
  77884. ColorCurves.Parse = function (source) {
  77885. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  77886. };
  77887. __decorate([
  77888. BABYLON.serialize()
  77889. ], ColorCurves.prototype, "_globalHue", void 0);
  77890. __decorate([
  77891. BABYLON.serialize()
  77892. ], ColorCurves.prototype, "_globalDensity", void 0);
  77893. __decorate([
  77894. BABYLON.serialize()
  77895. ], ColorCurves.prototype, "_globalSaturation", void 0);
  77896. __decorate([
  77897. BABYLON.serialize()
  77898. ], ColorCurves.prototype, "_globalExposure", void 0);
  77899. __decorate([
  77900. BABYLON.serialize()
  77901. ], ColorCurves.prototype, "_highlightsHue", void 0);
  77902. __decorate([
  77903. BABYLON.serialize()
  77904. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  77905. __decorate([
  77906. BABYLON.serialize()
  77907. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  77908. __decorate([
  77909. BABYLON.serialize()
  77910. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  77911. __decorate([
  77912. BABYLON.serialize()
  77913. ], ColorCurves.prototype, "_midtonesHue", void 0);
  77914. __decorate([
  77915. BABYLON.serialize()
  77916. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  77917. __decorate([
  77918. BABYLON.serialize()
  77919. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  77920. __decorate([
  77921. BABYLON.serialize()
  77922. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  77923. return ColorCurves;
  77924. }());
  77925. BABYLON.ColorCurves = ColorCurves;
  77926. })(BABYLON || (BABYLON = {}));
  77927. //# sourceMappingURL=babylon.colorCurves.js.map
  77928. var BABYLON;
  77929. (function (BABYLON) {
  77930. var RefractionPostProcess = /** @class */ (function (_super) {
  77931. __extends(RefractionPostProcess, _super);
  77932. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  77933. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  77934. _this.color = color;
  77935. _this.depth = depth;
  77936. _this.colorLevel = colorLevel;
  77937. _this._ownRefractionTexture = true;
  77938. _this.onActivateObservable.add(function (cam) {
  77939. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  77940. });
  77941. _this.onApplyObservable.add(function (effect) {
  77942. effect.setColor3("baseColor", _this.color);
  77943. effect.setFloat("depth", _this.depth);
  77944. effect.setFloat("colorLevel", _this.colorLevel);
  77945. effect.setTexture("refractionSampler", _this._refTexture);
  77946. });
  77947. return _this;
  77948. }
  77949. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  77950. /**
  77951. * Gets or sets the refraction texture
  77952. * Please note that you are responsible for disposing the texture if you set it manually
  77953. */
  77954. get: function () {
  77955. return this._refTexture;
  77956. },
  77957. set: function (value) {
  77958. if (this._refTexture && this._ownRefractionTexture) {
  77959. this._refTexture.dispose();
  77960. }
  77961. this._refTexture = value;
  77962. this._ownRefractionTexture = false;
  77963. },
  77964. enumerable: true,
  77965. configurable: true
  77966. });
  77967. // Methods
  77968. RefractionPostProcess.prototype.dispose = function (camera) {
  77969. if (this._refTexture && this._ownRefractionTexture) {
  77970. this._refTexture.dispose();
  77971. this._refTexture = null;
  77972. }
  77973. _super.prototype.dispose.call(this, camera);
  77974. };
  77975. return RefractionPostProcess;
  77976. }(BABYLON.PostProcess));
  77977. BABYLON.RefractionPostProcess = RefractionPostProcess;
  77978. })(BABYLON || (BABYLON = {}));
  77979. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  77980. var BABYLON;
  77981. (function (BABYLON) {
  77982. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  77983. __extends(BlackAndWhitePostProcess, _super);
  77984. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  77985. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  77986. _this.degree = 1;
  77987. _this.onApplyObservable.add(function (effect) {
  77988. effect.setFloat("degree", _this.degree);
  77989. });
  77990. return _this;
  77991. }
  77992. return BlackAndWhitePostProcess;
  77993. }(BABYLON.PostProcess));
  77994. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  77995. })(BABYLON || (BABYLON = {}));
  77996. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  77997. var BABYLON;
  77998. (function (BABYLON) {
  77999. /**
  78000. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78001. * input texture to perform effects such as edge detection or sharpening
  78002. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78003. */
  78004. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78005. __extends(ConvolutionPostProcess, _super);
  78006. /**
  78007. * Creates a new instance ConvolutionPostProcess
  78008. * @param name The name of the effect.
  78009. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78010. * @param options The required width/height ratio to downsize to before computing the render pass.
  78011. * @param camera The camera to apply the render pass to.
  78012. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78013. * @param engine The engine which the post process will be applied. (default: current engine)
  78014. * @param reusable If the post process can be reused on the same frame. (default: false)
  78015. * @param textureType Type of textures used when performing the post process. (default: 0)
  78016. */
  78017. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78018. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78019. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78020. _this.kernel = kernel;
  78021. _this.onApply = function (effect) {
  78022. effect.setFloat2("screenSize", _this.width, _this.height);
  78023. effect.setArray("kernel", _this.kernel);
  78024. };
  78025. return _this;
  78026. }
  78027. // Statics
  78028. /**
  78029. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78030. */
  78031. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78032. /**
  78033. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78034. */
  78035. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78036. /**
  78037. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78038. */
  78039. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78040. /**
  78041. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78042. */
  78043. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78044. /**
  78045. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78046. */
  78047. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78048. /**
  78049. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78050. */
  78051. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78052. return ConvolutionPostProcess;
  78053. }(BABYLON.PostProcess));
  78054. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78055. })(BABYLON || (BABYLON = {}));
  78056. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78057. var BABYLON;
  78058. (function (BABYLON) {
  78059. var FilterPostProcess = /** @class */ (function (_super) {
  78060. __extends(FilterPostProcess, _super);
  78061. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78062. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78063. _this.kernelMatrix = kernelMatrix;
  78064. _this.onApply = function (effect) {
  78065. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78066. };
  78067. return _this;
  78068. }
  78069. return FilterPostProcess;
  78070. }(BABYLON.PostProcess));
  78071. BABYLON.FilterPostProcess = FilterPostProcess;
  78072. })(BABYLON || (BABYLON = {}));
  78073. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78074. var BABYLON;
  78075. (function (BABYLON) {
  78076. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78077. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78078. __extends(VolumetricLightScatteringPostProcess, _super);
  78079. /**
  78080. * @constructor
  78081. * @param {string} name - The post-process name
  78082. * @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)
  78083. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78084. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78085. * @param {number} samples - The post-process quality, default 100
  78086. * @param {number} samplingMode - The post-process filtering mode
  78087. * @param {BABYLON.Engine} engine - The babylon engine
  78088. * @param {boolean} reusable - If the post-process is reusable
  78089. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78090. */
  78091. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78092. if (samples === void 0) { samples = 100; }
  78093. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78094. 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;
  78095. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78096. /**
  78097. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78098. */
  78099. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78100. /**
  78101. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78102. */
  78103. _this.useCustomMeshPosition = false;
  78104. /**
  78105. * If the post-process should inverse the light scattering direction
  78106. */
  78107. _this.invert = true;
  78108. /**
  78109. * Array containing the excluded meshes not rendered in the internal pass
  78110. */
  78111. _this.excludedMeshes = new Array();
  78112. /**
  78113. * Controls the overall intensity of the post-process
  78114. */
  78115. _this.exposure = 0.3;
  78116. /**
  78117. * Dissipates each sample's contribution in range [0, 1]
  78118. */
  78119. _this.decay = 0.96815;
  78120. /**
  78121. * Controls the overall intensity of each sample
  78122. */
  78123. _this.weight = 0.58767;
  78124. /**
  78125. * Controls the density of each sample
  78126. */
  78127. _this.density = 0.926;
  78128. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78129. engine = scene.getEngine();
  78130. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78131. // Configure mesh
  78132. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78133. // Configure
  78134. _this._createPass(scene, ratio.passRatio || ratio);
  78135. _this.onActivate = function (camera) {
  78136. if (!_this.isSupported) {
  78137. _this.dispose(camera);
  78138. }
  78139. _this.onActivate = null;
  78140. };
  78141. _this.onApplyObservable.add(function (effect) {
  78142. _this._updateMeshScreenCoordinates(scene);
  78143. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78144. effect.setFloat("exposure", _this.exposure);
  78145. effect.setFloat("decay", _this.decay);
  78146. effect.setFloat("weight", _this.weight);
  78147. effect.setFloat("density", _this.density);
  78148. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78149. });
  78150. return _this;
  78151. }
  78152. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78153. get: function () {
  78154. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78155. return false;
  78156. },
  78157. set: function (useDiffuseColor) {
  78158. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78159. },
  78160. enumerable: true,
  78161. configurable: true
  78162. });
  78163. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78164. return "VolumetricLightScatteringPostProcess";
  78165. };
  78166. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78167. var mesh = subMesh.getMesh();
  78168. // Render this.mesh as default
  78169. if (mesh === this.mesh && mesh.material) {
  78170. return mesh.material.isReady(mesh);
  78171. }
  78172. var defines = [];
  78173. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78174. var material = subMesh.getMaterial();
  78175. // Alpha test
  78176. if (material) {
  78177. if (material.needAlphaTesting()) {
  78178. defines.push("#define ALPHATEST");
  78179. }
  78180. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78181. attribs.push(BABYLON.VertexBuffer.UVKind);
  78182. defines.push("#define UV1");
  78183. }
  78184. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78185. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78186. defines.push("#define UV2");
  78187. }
  78188. }
  78189. // Bones
  78190. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78193. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78194. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78195. }
  78196. else {
  78197. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78198. }
  78199. // Instances
  78200. if (useInstances) {
  78201. defines.push("#define INSTANCES");
  78202. attribs.push("world0");
  78203. attribs.push("world1");
  78204. attribs.push("world2");
  78205. attribs.push("world3");
  78206. }
  78207. // Get correct effect
  78208. var join = defines.join("\n");
  78209. if (this._cachedDefines !== join) {
  78210. this._cachedDefines = join;
  78211. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78212. }
  78213. return this._volumetricLightScatteringPass.isReady();
  78214. };
  78215. /**
  78216. * Sets the new light position for light scattering effect
  78217. * @param {BABYLON.Vector3} The new custom light position
  78218. */
  78219. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78220. this.customMeshPosition = position;
  78221. };
  78222. /**
  78223. * Returns the light position for light scattering effect
  78224. * @return {BABYLON.Vector3} The custom light position
  78225. */
  78226. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78227. return this.customMeshPosition;
  78228. };
  78229. /**
  78230. * Disposes the internal assets and detaches the post-process from the camera
  78231. */
  78232. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78233. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78234. if (rttIndex !== -1) {
  78235. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78236. }
  78237. this._volumetricLightScatteringRTT.dispose();
  78238. _super.prototype.dispose.call(this, camera);
  78239. };
  78240. /**
  78241. * Returns the render target texture used by the post-process
  78242. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78243. */
  78244. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78245. return this._volumetricLightScatteringRTT;
  78246. };
  78247. // Private methods
  78248. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78249. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78250. return true;
  78251. }
  78252. return false;
  78253. };
  78254. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78255. var _this = this;
  78256. var engine = scene.getEngine();
  78257. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78258. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78259. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78260. this._volumetricLightScatteringRTT.renderList = null;
  78261. this._volumetricLightScatteringRTT.renderParticles = false;
  78262. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78263. var camera = this.getCamera();
  78264. if (camera) {
  78265. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78266. }
  78267. else {
  78268. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78269. }
  78270. // Custom render function for submeshes
  78271. var renderSubMesh = function (subMesh) {
  78272. var mesh = subMesh.getRenderingMesh();
  78273. if (_this._meshExcluded(mesh)) {
  78274. return;
  78275. }
  78276. var material = subMesh.getMaterial();
  78277. if (!material) {
  78278. return;
  78279. }
  78280. var scene = mesh.getScene();
  78281. var engine = scene.getEngine();
  78282. // Culling
  78283. engine.setState(material.backFaceCulling);
  78284. // Managing instances
  78285. var batch = mesh._getInstancesRenderList(subMesh._id);
  78286. if (batch.mustReturn) {
  78287. return;
  78288. }
  78289. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78290. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78291. var effect = _this._volumetricLightScatteringPass;
  78292. if (mesh === _this.mesh) {
  78293. if (subMesh.effect) {
  78294. effect = subMesh.effect;
  78295. }
  78296. else {
  78297. effect = material.getEffect();
  78298. }
  78299. }
  78300. engine.enableEffect(effect);
  78301. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78302. if (mesh === _this.mesh) {
  78303. material.bind(mesh.getWorldMatrix(), mesh);
  78304. }
  78305. else {
  78306. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78307. // Alpha test
  78308. if (material && material.needAlphaTesting()) {
  78309. var alphaTexture = material.getAlphaTestTexture();
  78310. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78311. if (alphaTexture) {
  78312. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78313. }
  78314. }
  78315. // Bones
  78316. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78317. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78318. }
  78319. }
  78320. // Draw
  78321. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78322. }
  78323. };
  78324. // Render target texture callbacks
  78325. var savedSceneClearColor;
  78326. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78327. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78328. savedSceneClearColor = scene.clearColor;
  78329. scene.clearColor = sceneClearColor;
  78330. });
  78331. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78332. scene.clearColor = savedSceneClearColor;
  78333. });
  78334. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78335. var engine = scene.getEngine();
  78336. var index;
  78337. if (depthOnlySubMeshes.length) {
  78338. engine.setColorWrite(false);
  78339. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78340. renderSubMesh(depthOnlySubMeshes.data[index]);
  78341. }
  78342. engine.setColorWrite(true);
  78343. }
  78344. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78345. renderSubMesh(opaqueSubMeshes.data[index]);
  78346. }
  78347. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78348. renderSubMesh(alphaTestSubMeshes.data[index]);
  78349. }
  78350. if (transparentSubMeshes.length) {
  78351. // Sort sub meshes
  78352. for (index = 0; index < transparentSubMeshes.length; index++) {
  78353. var submesh = transparentSubMeshes.data[index];
  78354. var boundingInfo = submesh.getBoundingInfo();
  78355. if (boundingInfo && scene.activeCamera) {
  78356. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78357. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78358. }
  78359. }
  78360. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78361. sortedArray.sort(function (a, b) {
  78362. // Alpha index first
  78363. if (a._alphaIndex > b._alphaIndex) {
  78364. return 1;
  78365. }
  78366. if (a._alphaIndex < b._alphaIndex) {
  78367. return -1;
  78368. }
  78369. // Then distance to camera
  78370. if (a._distanceToCamera < b._distanceToCamera) {
  78371. return 1;
  78372. }
  78373. if (a._distanceToCamera > b._distanceToCamera) {
  78374. return -1;
  78375. }
  78376. return 0;
  78377. });
  78378. // Render sub meshes
  78379. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78380. for (index = 0; index < sortedArray.length; index++) {
  78381. renderSubMesh(sortedArray[index]);
  78382. }
  78383. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78384. }
  78385. };
  78386. };
  78387. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78388. var transform = scene.getTransformMatrix();
  78389. var meshPosition;
  78390. if (this.useCustomMeshPosition) {
  78391. meshPosition = this.customMeshPosition;
  78392. }
  78393. else if (this.attachedNode) {
  78394. meshPosition = this.attachedNode.position;
  78395. }
  78396. else {
  78397. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78398. }
  78399. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78400. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78401. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78402. if (this.invert)
  78403. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78404. };
  78405. // Static methods
  78406. /**
  78407. * Creates a default mesh for the Volumeric Light Scattering post-process
  78408. * @param {string} The mesh name
  78409. * @param {BABYLON.Scene} The scene where to create the mesh
  78410. * @return {BABYLON.Mesh} the default mesh
  78411. */
  78412. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78413. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78414. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78415. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78416. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78417. mesh.material = material;
  78418. return mesh;
  78419. };
  78420. __decorate([
  78421. BABYLON.serializeAsVector3()
  78422. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78423. __decorate([
  78424. BABYLON.serialize()
  78425. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78426. __decorate([
  78427. BABYLON.serialize()
  78428. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78429. __decorate([
  78430. BABYLON.serializeAsMeshReference()
  78431. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78432. __decorate([
  78433. BABYLON.serialize()
  78434. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78435. __decorate([
  78436. BABYLON.serialize()
  78437. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78438. __decorate([
  78439. BABYLON.serialize()
  78440. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78441. __decorate([
  78442. BABYLON.serialize()
  78443. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78444. __decorate([
  78445. BABYLON.serialize()
  78446. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78447. return VolumetricLightScatteringPostProcess;
  78448. }(BABYLON.PostProcess));
  78449. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78450. })(BABYLON || (BABYLON = {}));
  78451. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78452. //
  78453. // This post-process allows the modification of rendered colors by using
  78454. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78455. //
  78456. // The object needs to be provided an url to a texture containing the color
  78457. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78458. // Use an image editing software to tweak the LUT to match your needs.
  78459. //
  78460. // For an example of a color LUT, see here:
  78461. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78462. // For explanations on color grading, see here:
  78463. // http://udn.epicgames.com/Three/ColorGrading.html
  78464. //
  78465. var BABYLON;
  78466. (function (BABYLON) {
  78467. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78468. __extends(ColorCorrectionPostProcess, _super);
  78469. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78470. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78471. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78472. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78473. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78474. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78475. _this.onApply = function (effect) {
  78476. effect.setTexture("colorTable", _this._colorTableTexture);
  78477. };
  78478. return _this;
  78479. }
  78480. return ColorCorrectionPostProcess;
  78481. }(BABYLON.PostProcess));
  78482. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78483. })(BABYLON || (BABYLON = {}));
  78484. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78485. var BABYLON;
  78486. (function (BABYLON) {
  78487. /** Defines operator used for tonemapping */
  78488. var TonemappingOperator;
  78489. (function (TonemappingOperator) {
  78490. /** Hable */
  78491. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78492. /** Reinhard */
  78493. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78494. /** HejiDawson */
  78495. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78496. /** Photographic */
  78497. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78498. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78499. ;
  78500. /**
  78501. * Defines a post process to apply tone mapping
  78502. */
  78503. var TonemapPostProcess = /** @class */ (function (_super) {
  78504. __extends(TonemapPostProcess, _super);
  78505. /**
  78506. * Creates a new TonemapPostProcess
  78507. * @param name defines the name of the postprocess
  78508. * @param _operator defines the operator to use
  78509. * @param exposureAdjustment defines the required exposure adjustement
  78510. * @param camera defines the camera to use (can be null)
  78511. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78512. * @param engine defines the hosting engine (can be ignore if camera is set)
  78513. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78514. */
  78515. function TonemapPostProcess(name, _operator,
  78516. /** Defines the required exposure adjustement */
  78517. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78518. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78519. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78520. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78521. _this._operator = _operator;
  78522. _this.exposureAdjustment = exposureAdjustment;
  78523. var defines = "#define ";
  78524. if (_this._operator === TonemappingOperator.Hable)
  78525. defines += "HABLE_TONEMAPPING";
  78526. else if (_this._operator === TonemappingOperator.Reinhard)
  78527. defines += "REINHARD_TONEMAPPING";
  78528. else if (_this._operator === TonemappingOperator.HejiDawson)
  78529. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78530. else if (_this._operator === TonemappingOperator.Photographic)
  78531. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78532. //sadly a second call to create the effect.
  78533. _this.updateEffect(defines);
  78534. _this.onApply = function (effect) {
  78535. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78536. };
  78537. return _this;
  78538. }
  78539. return TonemapPostProcess;
  78540. }(BABYLON.PostProcess));
  78541. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78542. })(BABYLON || (BABYLON = {}));
  78543. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78544. var BABYLON;
  78545. (function (BABYLON) {
  78546. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78547. __extends(DisplayPassPostProcess, _super);
  78548. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78549. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78550. }
  78551. return DisplayPassPostProcess;
  78552. }(BABYLON.PostProcess));
  78553. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78554. })(BABYLON || (BABYLON = {}));
  78555. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78556. var BABYLON;
  78557. (function (BABYLON) {
  78558. var HighlightsPostProcess = /** @class */ (function (_super) {
  78559. __extends(HighlightsPostProcess, _super);
  78560. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78561. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78562. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78563. }
  78564. return HighlightsPostProcess;
  78565. }(BABYLON.PostProcess));
  78566. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78567. })(BABYLON || (BABYLON = {}));
  78568. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78569. var BABYLON;
  78570. (function (BABYLON) {
  78571. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78572. __extends(ImageProcessingPostProcess, _super);
  78573. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78574. if (camera === void 0) { camera = null; }
  78575. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78576. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78577. _this._fromLinearSpace = true;
  78578. /**
  78579. * Defines cache preventing GC.
  78580. */
  78581. _this._defines = {
  78582. IMAGEPROCESSING: false,
  78583. VIGNETTE: false,
  78584. VIGNETTEBLENDMODEMULTIPLY: false,
  78585. VIGNETTEBLENDMODEOPAQUE: false,
  78586. TONEMAPPING: false,
  78587. CONTRAST: false,
  78588. COLORCURVES: false,
  78589. COLORGRADING: false,
  78590. COLORGRADING3D: false,
  78591. FROMLINEARSPACE: false,
  78592. SAMPLER3DGREENDEPTH: false,
  78593. SAMPLER3DBGRMAP: false,
  78594. IMAGEPROCESSINGPOSTPROCESS: false,
  78595. EXPOSURE: false,
  78596. };
  78597. // Setup the configuration as forced by the constructor. This would then not force the
  78598. // scene materials output in linear space and let untouched the default forward pass.
  78599. if (imageProcessingConfiguration) {
  78600. imageProcessingConfiguration.applyByPostProcess = true;
  78601. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78602. // This will cause the shader to be compiled
  78603. _this.fromLinearSpace = false;
  78604. }
  78605. // Setup the default processing configuration to the scene.
  78606. else {
  78607. _this._attachImageProcessingConfiguration(null, true);
  78608. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78609. }
  78610. _this.onApply = function (effect) {
  78611. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78612. };
  78613. return _this;
  78614. }
  78615. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78616. /**
  78617. * Gets the image processing configuration used either in this material.
  78618. */
  78619. get: function () {
  78620. return this._imageProcessingConfiguration;
  78621. },
  78622. /**
  78623. * Sets the Default image processing configuration used either in the this material.
  78624. *
  78625. * If sets to null, the scene one is in use.
  78626. */
  78627. set: function (value) {
  78628. this._attachImageProcessingConfiguration(value);
  78629. },
  78630. enumerable: true,
  78631. configurable: true
  78632. });
  78633. /**
  78634. * Attaches a new image processing configuration to the PBR Material.
  78635. * @param configuration
  78636. */
  78637. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78638. var _this = this;
  78639. if (doNotBuild === void 0) { doNotBuild = false; }
  78640. if (configuration === this._imageProcessingConfiguration) {
  78641. return;
  78642. }
  78643. // Detaches observer.
  78644. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78645. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78646. }
  78647. // Pick the scene configuration if needed.
  78648. if (!configuration) {
  78649. var scene = null;
  78650. var engine = this.getEngine();
  78651. var camera = this.getCamera();
  78652. if (camera) {
  78653. scene = camera.getScene();
  78654. }
  78655. else if (engine && engine.scenes) {
  78656. var scenes = engine.scenes;
  78657. scene = scenes[scenes.length - 1];
  78658. }
  78659. else {
  78660. scene = BABYLON.Engine.LastCreatedScene;
  78661. }
  78662. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78663. }
  78664. else {
  78665. this._imageProcessingConfiguration = configuration;
  78666. }
  78667. // Attaches observer.
  78668. if (this._imageProcessingConfiguration) {
  78669. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78670. _this._updateParameters();
  78671. });
  78672. }
  78673. // Ensure the effect will be rebuilt.
  78674. if (!doNotBuild) {
  78675. this._updateParameters();
  78676. }
  78677. };
  78678. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78679. /**
  78680. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78681. */
  78682. get: function () {
  78683. return this.imageProcessingConfiguration.colorCurves;
  78684. },
  78685. /**
  78686. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78687. */
  78688. set: function (value) {
  78689. this.imageProcessingConfiguration.colorCurves = value;
  78690. },
  78691. enumerable: true,
  78692. configurable: true
  78693. });
  78694. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  78695. /**
  78696. * Gets wether the color curves effect is enabled.
  78697. */
  78698. get: function () {
  78699. return this.imageProcessingConfiguration.colorCurvesEnabled;
  78700. },
  78701. /**
  78702. * Sets wether the color curves effect is enabled.
  78703. */
  78704. set: function (value) {
  78705. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  78706. },
  78707. enumerable: true,
  78708. configurable: true
  78709. });
  78710. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  78711. /**
  78712. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78713. */
  78714. get: function () {
  78715. return this.imageProcessingConfiguration.colorGradingTexture;
  78716. },
  78717. /**
  78718. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  78719. */
  78720. set: function (value) {
  78721. this.imageProcessingConfiguration.colorGradingTexture = value;
  78722. },
  78723. enumerable: true,
  78724. configurable: true
  78725. });
  78726. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  78727. /**
  78728. * Gets wether the color grading effect is enabled.
  78729. */
  78730. get: function () {
  78731. return this.imageProcessingConfiguration.colorGradingEnabled;
  78732. },
  78733. /**
  78734. * Gets wether the color grading effect is enabled.
  78735. */
  78736. set: function (value) {
  78737. this.imageProcessingConfiguration.colorGradingEnabled = value;
  78738. },
  78739. enumerable: true,
  78740. configurable: true
  78741. });
  78742. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  78743. /**
  78744. * Gets exposure used in the effect.
  78745. */
  78746. get: function () {
  78747. return this.imageProcessingConfiguration.exposure;
  78748. },
  78749. /**
  78750. * Sets exposure used in the effect.
  78751. */
  78752. set: function (value) {
  78753. this.imageProcessingConfiguration.exposure = value;
  78754. },
  78755. enumerable: true,
  78756. configurable: true
  78757. });
  78758. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  78759. /**
  78760. * Gets wether tonemapping is enabled or not.
  78761. */
  78762. get: function () {
  78763. return this._imageProcessingConfiguration.toneMappingEnabled;
  78764. },
  78765. /**
  78766. * Sets wether tonemapping is enabled or not
  78767. */
  78768. set: function (value) {
  78769. this._imageProcessingConfiguration.toneMappingEnabled = value;
  78770. },
  78771. enumerable: true,
  78772. configurable: true
  78773. });
  78774. ;
  78775. ;
  78776. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  78777. /**
  78778. * Gets contrast used in the effect.
  78779. */
  78780. get: function () {
  78781. return this.imageProcessingConfiguration.contrast;
  78782. },
  78783. /**
  78784. * Sets contrast used in the effect.
  78785. */
  78786. set: function (value) {
  78787. this.imageProcessingConfiguration.contrast = value;
  78788. },
  78789. enumerable: true,
  78790. configurable: true
  78791. });
  78792. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  78793. /**
  78794. * Gets Vignette stretch size.
  78795. */
  78796. get: function () {
  78797. return this.imageProcessingConfiguration.vignetteStretch;
  78798. },
  78799. /**
  78800. * Sets Vignette stretch size.
  78801. */
  78802. set: function (value) {
  78803. this.imageProcessingConfiguration.vignetteStretch = value;
  78804. },
  78805. enumerable: true,
  78806. configurable: true
  78807. });
  78808. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  78809. /**
  78810. * Gets Vignette centre X Offset.
  78811. */
  78812. get: function () {
  78813. return this.imageProcessingConfiguration.vignetteCentreX;
  78814. },
  78815. /**
  78816. * Sets Vignette centre X Offset.
  78817. */
  78818. set: function (value) {
  78819. this.imageProcessingConfiguration.vignetteCentreX = value;
  78820. },
  78821. enumerable: true,
  78822. configurable: true
  78823. });
  78824. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  78825. /**
  78826. * Gets Vignette centre Y Offset.
  78827. */
  78828. get: function () {
  78829. return this.imageProcessingConfiguration.vignetteCentreY;
  78830. },
  78831. /**
  78832. * Sets Vignette centre Y Offset.
  78833. */
  78834. set: function (value) {
  78835. this.imageProcessingConfiguration.vignetteCentreY = value;
  78836. },
  78837. enumerable: true,
  78838. configurable: true
  78839. });
  78840. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  78841. /**
  78842. * Gets Vignette weight or intensity of the vignette effect.
  78843. */
  78844. get: function () {
  78845. return this.imageProcessingConfiguration.vignetteWeight;
  78846. },
  78847. /**
  78848. * Sets Vignette weight or intensity of the vignette effect.
  78849. */
  78850. set: function (value) {
  78851. this.imageProcessingConfiguration.vignetteWeight = value;
  78852. },
  78853. enumerable: true,
  78854. configurable: true
  78855. });
  78856. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  78857. /**
  78858. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78859. * if vignetteEnabled is set to true.
  78860. */
  78861. get: function () {
  78862. return this.imageProcessingConfiguration.vignetteColor;
  78863. },
  78864. /**
  78865. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  78866. * if vignetteEnabled is set to true.
  78867. */
  78868. set: function (value) {
  78869. this.imageProcessingConfiguration.vignetteColor = value;
  78870. },
  78871. enumerable: true,
  78872. configurable: true
  78873. });
  78874. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  78875. /**
  78876. * Gets Camera field of view used by the Vignette effect.
  78877. */
  78878. get: function () {
  78879. return this.imageProcessingConfiguration.vignetteCameraFov;
  78880. },
  78881. /**
  78882. * Sets Camera field of view used by the Vignette effect.
  78883. */
  78884. set: function (value) {
  78885. this.imageProcessingConfiguration.vignetteCameraFov = value;
  78886. },
  78887. enumerable: true,
  78888. configurable: true
  78889. });
  78890. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  78891. /**
  78892. * Gets the vignette blend mode allowing different kind of effect.
  78893. */
  78894. get: function () {
  78895. return this.imageProcessingConfiguration.vignetteBlendMode;
  78896. },
  78897. /**
  78898. * Sets the vignette blend mode allowing different kind of effect.
  78899. */
  78900. set: function (value) {
  78901. this.imageProcessingConfiguration.vignetteBlendMode = value;
  78902. },
  78903. enumerable: true,
  78904. configurable: true
  78905. });
  78906. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  78907. /**
  78908. * Gets wether the vignette effect is enabled.
  78909. */
  78910. get: function () {
  78911. return this.imageProcessingConfiguration.vignetteEnabled;
  78912. },
  78913. /**
  78914. * Sets wether the vignette effect is enabled.
  78915. */
  78916. set: function (value) {
  78917. this.imageProcessingConfiguration.vignetteEnabled = value;
  78918. },
  78919. enumerable: true,
  78920. configurable: true
  78921. });
  78922. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  78923. /**
  78924. * Gets wether the input of the processing is in Gamma or Linear Space.
  78925. */
  78926. get: function () {
  78927. return this._fromLinearSpace;
  78928. },
  78929. /**
  78930. * Sets wether the input of the processing is in Gamma or Linear Space.
  78931. */
  78932. set: function (value) {
  78933. if (this._fromLinearSpace === value) {
  78934. return;
  78935. }
  78936. this._fromLinearSpace = value;
  78937. this._updateParameters();
  78938. },
  78939. enumerable: true,
  78940. configurable: true
  78941. });
  78942. ImageProcessingPostProcess.prototype.getClassName = function () {
  78943. return "ImageProcessingPostProcess";
  78944. };
  78945. ImageProcessingPostProcess.prototype._updateParameters = function () {
  78946. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  78947. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  78948. var defines = "";
  78949. for (var define in this._defines) {
  78950. if (this._defines[define]) {
  78951. defines += "#define " + define + ";\r\n";
  78952. }
  78953. }
  78954. var samplers = ["textureSampler"];
  78955. var uniforms = ["scale"];
  78956. if (BABYLON.ImageProcessingConfiguration) {
  78957. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  78958. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  78959. }
  78960. this.updateEffect(defines, uniforms, samplers);
  78961. };
  78962. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  78963. _super.prototype.dispose.call(this, camera);
  78964. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78965. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78966. }
  78967. if (this._imageProcessingConfiguration) {
  78968. this.imageProcessingConfiguration.applyByPostProcess = false;
  78969. }
  78970. };
  78971. __decorate([
  78972. BABYLON.serialize()
  78973. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  78974. return ImageProcessingPostProcess;
  78975. }(BABYLON.PostProcess));
  78976. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  78977. })(BABYLON || (BABYLON = {}));
  78978. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  78979. var BABYLON;
  78980. (function (BABYLON) {
  78981. /**
  78982. * Class used to store bone information
  78983. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78984. */
  78985. var Bone = /** @class */ (function (_super) {
  78986. __extends(Bone, _super);
  78987. /**
  78988. * Create a new bone
  78989. * @param name defines the bone name
  78990. * @param skeleton defines the parent skeleton
  78991. * @param parentBone defines the parent (can be null if the bone is the root)
  78992. * @param localMatrix defines the local matrix
  78993. * @param restPose defines the rest pose matrix
  78994. * @param baseMatrix defines the base matrix
  78995. * @param index defines index of the bone in the hiearchy
  78996. */
  78997. function Bone(
  78998. /**
  78999. * defines the bone name
  79000. */
  79001. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79002. if (parentBone === void 0) { parentBone = null; }
  79003. if (localMatrix === void 0) { localMatrix = null; }
  79004. if (restPose === void 0) { restPose = null; }
  79005. if (baseMatrix === void 0) { baseMatrix = null; }
  79006. if (index === void 0) { index = null; }
  79007. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79008. _this.name = name;
  79009. /**
  79010. * Gets the list of child bones
  79011. */
  79012. _this.children = new Array();
  79013. /** Gets the animations associated with this bone */
  79014. _this.animations = new Array();
  79015. /**
  79016. * @hidden Internal only
  79017. * Set this value to map this bone to a different index in the transform matrices
  79018. * Set this value to -1 to exclude the bone from the transform matrices
  79019. */
  79020. _this._index = null;
  79021. _this._absoluteTransform = new BABYLON.Matrix();
  79022. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79023. _this._scalingDeterminant = 1;
  79024. _this._worldTransform = new BABYLON.Matrix();
  79025. _this._needToDecompose = true;
  79026. _this._needToCompose = false;
  79027. _this._skeleton = skeleton;
  79028. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79029. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79030. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79031. _this._index = index;
  79032. skeleton.bones.push(_this);
  79033. _this.setParent(parentBone, false);
  79034. if (baseMatrix || localMatrix) {
  79035. _this._updateDifferenceMatrix();
  79036. }
  79037. return _this;
  79038. }
  79039. Object.defineProperty(Bone.prototype, "_matrix", {
  79040. /** @hidden */
  79041. get: function () {
  79042. this._compose();
  79043. return this._localMatrix;
  79044. },
  79045. /** @hidden */
  79046. set: function (value) {
  79047. this._localMatrix.copyFrom(value);
  79048. this._needToDecompose = true;
  79049. },
  79050. enumerable: true,
  79051. configurable: true
  79052. });
  79053. // Members
  79054. /**
  79055. * Gets the parent skeleton
  79056. * @returns a skeleton
  79057. */
  79058. Bone.prototype.getSkeleton = function () {
  79059. return this._skeleton;
  79060. };
  79061. /**
  79062. * Gets parent bone
  79063. * @returns a bone or null if the bone is the root of the bone hierarchy
  79064. */
  79065. Bone.prototype.getParent = function () {
  79066. return this._parent;
  79067. };
  79068. /**
  79069. * Sets the parent bone
  79070. * @param parent defines the parent (can be null if the bone is the root)
  79071. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79072. */
  79073. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79074. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79075. if (this._parent === parent) {
  79076. return;
  79077. }
  79078. if (this._parent) {
  79079. var index = this._parent.children.indexOf(this);
  79080. if (index !== -1) {
  79081. this._parent.children.splice(index, 1);
  79082. }
  79083. }
  79084. this._parent = parent;
  79085. if (this._parent) {
  79086. this._parent.children.push(this);
  79087. }
  79088. if (updateDifferenceMatrix) {
  79089. this._updateDifferenceMatrix();
  79090. }
  79091. this.markAsDirty();
  79092. };
  79093. /**
  79094. * Gets the local matrix
  79095. * @returns a matrix
  79096. */
  79097. Bone.prototype.getLocalMatrix = function () {
  79098. this._compose();
  79099. return this._localMatrix;
  79100. };
  79101. /**
  79102. * Gets the base matrix (initial matrix which remains unchanged)
  79103. * @returns a matrix
  79104. */
  79105. Bone.prototype.getBaseMatrix = function () {
  79106. return this._baseMatrix;
  79107. };
  79108. /**
  79109. * Gets the rest pose matrix
  79110. * @returns a matrix
  79111. */
  79112. Bone.prototype.getRestPose = function () {
  79113. return this._restPose;
  79114. };
  79115. /**
  79116. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79117. */
  79118. Bone.prototype.getWorldMatrix = function () {
  79119. return this._worldTransform;
  79120. };
  79121. /**
  79122. * Sets the local matrix to rest pose matrix
  79123. */
  79124. Bone.prototype.returnToRest = function () {
  79125. this.updateMatrix(this._restPose.clone());
  79126. };
  79127. /**
  79128. * Gets the inverse of the absolute transform matrix.
  79129. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79130. * @returns a matrix
  79131. */
  79132. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79133. return this._invertedAbsoluteTransform;
  79134. };
  79135. /**
  79136. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79137. * @returns a matrix
  79138. */
  79139. Bone.prototype.getAbsoluteTransform = function () {
  79140. return this._absoluteTransform;
  79141. };
  79142. Object.defineProperty(Bone.prototype, "position", {
  79143. // Properties (matches AbstractMesh properties)
  79144. /** Gets or sets current position (in local space) */
  79145. get: function () {
  79146. this._decompose();
  79147. return this._localPosition;
  79148. },
  79149. set: function (newPosition) {
  79150. this._decompose();
  79151. this._localPosition.copyFrom(newPosition);
  79152. this._markAsDirtyAndCompose();
  79153. },
  79154. enumerable: true,
  79155. configurable: true
  79156. });
  79157. Object.defineProperty(Bone.prototype, "rotation", {
  79158. /** Gets or sets current rotation (in local space) */
  79159. get: function () {
  79160. return this.getRotation();
  79161. },
  79162. set: function (newRotation) {
  79163. this.setRotation(newRotation);
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79169. /** Gets or sets current rotation quaternion (in local space) */
  79170. get: function () {
  79171. this._decompose();
  79172. return this._localRotation;
  79173. },
  79174. set: function (newRotation) {
  79175. this.setRotationQuaternion(newRotation);
  79176. },
  79177. enumerable: true,
  79178. configurable: true
  79179. });
  79180. Object.defineProperty(Bone.prototype, "scaling", {
  79181. /** Gets or sets current scaling (in local space) */
  79182. get: function () {
  79183. return this.getScale();
  79184. },
  79185. set: function (newScaling) {
  79186. this.setScale(newScaling);
  79187. },
  79188. enumerable: true,
  79189. configurable: true
  79190. });
  79191. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79192. /**
  79193. * Gets the animation properties override
  79194. */
  79195. get: function () {
  79196. return this._skeleton.animationPropertiesOverride;
  79197. },
  79198. enumerable: true,
  79199. configurable: true
  79200. });
  79201. // Methods
  79202. Bone.prototype._decompose = function () {
  79203. if (!this._needToDecompose) {
  79204. return;
  79205. }
  79206. this._needToDecompose = false;
  79207. if (!this._localScaling) {
  79208. this._localScaling = BABYLON.Vector3.Zero();
  79209. this._localRotation = BABYLON.Quaternion.Zero();
  79210. this._localPosition = BABYLON.Vector3.Zero();
  79211. }
  79212. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79213. };
  79214. Bone.prototype._compose = function () {
  79215. if (!this._needToCompose) {
  79216. return;
  79217. }
  79218. this._needToCompose = false;
  79219. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79220. };
  79221. /**
  79222. * Update the base and local matrices
  79223. * @param matrix defines the new base or local matrix
  79224. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79225. * @param updateLocalMatrix defines if the local matrix should be updated
  79226. */
  79227. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79228. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79229. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79230. this._baseMatrix.copyFrom(matrix);
  79231. if (updateDifferenceMatrix) {
  79232. this._updateDifferenceMatrix();
  79233. }
  79234. if (updateLocalMatrix) {
  79235. this._localMatrix.copyFrom(matrix);
  79236. this._markAsDirtyAndDecompose();
  79237. }
  79238. else {
  79239. this.markAsDirty();
  79240. }
  79241. };
  79242. /** @hidden */
  79243. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79244. if (updateChildren === void 0) { updateChildren = true; }
  79245. if (!rootMatrix) {
  79246. rootMatrix = this._baseMatrix;
  79247. }
  79248. if (this._parent) {
  79249. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79250. }
  79251. else {
  79252. this._absoluteTransform.copyFrom(rootMatrix);
  79253. }
  79254. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79255. if (updateChildren) {
  79256. for (var index = 0; index < this.children.length; index++) {
  79257. this.children[index]._updateDifferenceMatrix();
  79258. }
  79259. }
  79260. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79261. };
  79262. /**
  79263. * Flag the bone as dirty (Forcing it to update everything)
  79264. */
  79265. Bone.prototype.markAsDirty = function () {
  79266. this._currentRenderId++;
  79267. this._childRenderId++;
  79268. this._skeleton._markAsDirty();
  79269. };
  79270. Bone.prototype._markAsDirtyAndCompose = function () {
  79271. this.markAsDirty();
  79272. this._needToCompose = true;
  79273. };
  79274. Bone.prototype._markAsDirtyAndDecompose = function () {
  79275. this.markAsDirty();
  79276. this._needToDecompose = true;
  79277. };
  79278. /**
  79279. * Copy an animation range from another bone
  79280. * @param source defines the source bone
  79281. * @param rangeName defines the range name to copy
  79282. * @param frameOffset defines the frame offset
  79283. * @param rescaleAsRequired defines if rescaling must be applied if required
  79284. * @param skelDimensionsRatio defines the scaling ratio
  79285. * @returns true if operation was successful
  79286. */
  79287. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79288. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79289. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79290. // all animation may be coming from a library skeleton, so may need to create animation
  79291. if (this.animations.length === 0) {
  79292. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79293. this.animations[0].setKeys([]);
  79294. }
  79295. // get animation info / verify there is such a range from the source bone
  79296. var sourceRange = source.animations[0].getRange(rangeName);
  79297. if (!sourceRange) {
  79298. return false;
  79299. }
  79300. var from = sourceRange.from;
  79301. var to = sourceRange.to;
  79302. var sourceKeys = source.animations[0].getKeys();
  79303. // rescaling prep
  79304. var sourceBoneLength = source.length;
  79305. var sourceParent = source.getParent();
  79306. var parent = this.getParent();
  79307. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79308. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79309. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79310. var destKeys = this.animations[0].getKeys();
  79311. // loop vars declaration
  79312. var orig;
  79313. var origTranslation;
  79314. var mat;
  79315. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79316. orig = sourceKeys[key];
  79317. if (orig.frame >= from && orig.frame <= to) {
  79318. if (rescaleAsRequired) {
  79319. mat = orig.value.clone();
  79320. // scale based on parent ratio, when bone has parent
  79321. if (parentScalingReqd) {
  79322. origTranslation = mat.getTranslation();
  79323. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79324. // scale based on skeleton dimension ratio when root bone, and value is passed
  79325. }
  79326. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79327. origTranslation = mat.getTranslation();
  79328. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79329. // use original when root bone, and no data for skelDimensionsRatio
  79330. }
  79331. else {
  79332. mat = orig.value;
  79333. }
  79334. }
  79335. else {
  79336. mat = orig.value;
  79337. }
  79338. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79339. }
  79340. }
  79341. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79342. return true;
  79343. };
  79344. /**
  79345. * Translate the bone in local or world space
  79346. * @param vec The amount to translate the bone
  79347. * @param space The space that the translation is in
  79348. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79349. */
  79350. Bone.prototype.translate = function (vec, space, mesh) {
  79351. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79352. var lm = this.getLocalMatrix();
  79353. if (space == BABYLON.Space.LOCAL) {
  79354. lm.m[12] += vec.x;
  79355. lm.m[13] += vec.y;
  79356. lm.m[14] += vec.z;
  79357. }
  79358. else {
  79359. var wm = null;
  79360. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79361. if (mesh) {
  79362. wm = mesh.getWorldMatrix();
  79363. }
  79364. this._skeleton.computeAbsoluteTransforms();
  79365. var tmat = Bone._tmpMats[0];
  79366. var tvec = Bone._tmpVecs[0];
  79367. if (this._parent) {
  79368. if (mesh && wm) {
  79369. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79370. tmat.multiplyToRef(wm, tmat);
  79371. }
  79372. else {
  79373. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79374. }
  79375. }
  79376. tmat.m[12] = 0;
  79377. tmat.m[13] = 0;
  79378. tmat.m[14] = 0;
  79379. tmat.invert();
  79380. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79381. lm.m[12] += tvec.x;
  79382. lm.m[13] += tvec.y;
  79383. lm.m[14] += tvec.z;
  79384. }
  79385. this._markAsDirtyAndDecompose();
  79386. };
  79387. /**
  79388. * Set the postion of the bone in local or world space
  79389. * @param position The position to set the bone
  79390. * @param space The space that the position is in
  79391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79392. */
  79393. Bone.prototype.setPosition = function (position, space, mesh) {
  79394. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79395. var lm = this.getLocalMatrix();
  79396. if (space == BABYLON.Space.LOCAL) {
  79397. lm.m[12] = position.x;
  79398. lm.m[13] = position.y;
  79399. lm.m[14] = position.z;
  79400. }
  79401. else {
  79402. var wm = null;
  79403. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79404. if (mesh) {
  79405. wm = mesh.getWorldMatrix();
  79406. }
  79407. this._skeleton.computeAbsoluteTransforms();
  79408. var tmat = Bone._tmpMats[0];
  79409. var vec = Bone._tmpVecs[0];
  79410. if (this._parent) {
  79411. if (mesh && wm) {
  79412. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79413. tmat.multiplyToRef(wm, tmat);
  79414. }
  79415. else {
  79416. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79417. }
  79418. }
  79419. tmat.invert();
  79420. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79421. lm.m[12] = vec.x;
  79422. lm.m[13] = vec.y;
  79423. lm.m[14] = vec.z;
  79424. }
  79425. this._markAsDirtyAndDecompose();
  79426. };
  79427. /**
  79428. * Set the absolute position of the bone (world space)
  79429. * @param position The position to set the bone
  79430. * @param mesh The mesh that this bone is attached to
  79431. */
  79432. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79433. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79434. };
  79435. /**
  79436. * Scale the bone on the x, y and z axes (in local space)
  79437. * @param x The amount to scale the bone on the x axis
  79438. * @param y The amount to scale the bone on the y axis
  79439. * @param z The amount to scale the bone on the z axis
  79440. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79441. */
  79442. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79443. if (scaleChildren === void 0) { scaleChildren = false; }
  79444. var locMat = this.getLocalMatrix();
  79445. // Apply new scaling on top of current local matrix
  79446. var scaleMat = Bone._tmpMats[0];
  79447. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79448. scaleMat.multiplyToRef(locMat, locMat);
  79449. // Invert scaling matrix and apply the inverse to all children
  79450. scaleMat.invert();
  79451. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79452. var child = _a[_i];
  79453. var cm = child.getLocalMatrix();
  79454. cm.multiplyToRef(scaleMat, cm);
  79455. cm.m[12] *= x;
  79456. cm.m[13] *= y;
  79457. cm.m[14] *= z;
  79458. child._markAsDirtyAndDecompose();
  79459. }
  79460. this._markAsDirtyAndDecompose();
  79461. if (scaleChildren) {
  79462. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79463. var child = _c[_b];
  79464. child.scale(x, y, z, scaleChildren);
  79465. }
  79466. }
  79467. };
  79468. /**
  79469. * Set the bone scaling in local space
  79470. * @param scale defines the scaling vector
  79471. */
  79472. Bone.prototype.setScale = function (scale) {
  79473. this._decompose();
  79474. this._localScaling.copyFrom(scale);
  79475. this._markAsDirtyAndCompose();
  79476. };
  79477. /**
  79478. * Gets the current scaling in local space
  79479. * @returns the current scaling vector
  79480. */
  79481. Bone.prototype.getScale = function () {
  79482. this._decompose();
  79483. return this._localScaling;
  79484. };
  79485. /**
  79486. * Gets the current scaling in local space and stores it in a target vector
  79487. * @param result defines the target vector
  79488. */
  79489. Bone.prototype.getScaleToRef = function (result) {
  79490. this._decompose();
  79491. result.copyFrom(this._localScaling);
  79492. };
  79493. /**
  79494. * Set the yaw, pitch, and roll of the bone in local or world space
  79495. * @param yaw The rotation of the bone on the y axis
  79496. * @param pitch The rotation of the bone on the x axis
  79497. * @param roll The rotation of the bone on the z axis
  79498. * @param space The space that the axes of rotation are in
  79499. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79500. */
  79501. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79502. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79503. if (space === BABYLON.Space.LOCAL) {
  79504. var quat = Bone._tmpQuat;
  79505. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79506. this.setRotationQuaternion(quat, space, mesh);
  79507. return;
  79508. }
  79509. var rotMatInv = Bone._tmpMats[0];
  79510. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79511. return;
  79512. }
  79513. var rotMat = Bone._tmpMats[1];
  79514. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79515. rotMatInv.multiplyToRef(rotMat, rotMat);
  79516. this._rotateWithMatrix(rotMat, space, mesh);
  79517. };
  79518. /**
  79519. * Add a rotation to the bone on an axis in local or world space
  79520. * @param axis The axis to rotate the bone on
  79521. * @param amount The amount to rotate the bone
  79522. * @param space The space that the axis is in
  79523. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79524. */
  79525. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79526. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79527. var rmat = Bone._tmpMats[0];
  79528. rmat.m[12] = 0;
  79529. rmat.m[13] = 0;
  79530. rmat.m[14] = 0;
  79531. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79532. this._rotateWithMatrix(rmat, space, mesh);
  79533. };
  79534. /**
  79535. * Set the rotation of the bone to a particular axis angle in local or world space
  79536. * @param axis The axis to rotate the bone on
  79537. * @param angle The angle that the bone should be rotated to
  79538. * @param space The space that the axis is in
  79539. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79540. */
  79541. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79542. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79543. if (space === BABYLON.Space.LOCAL) {
  79544. var quat = Bone._tmpQuat;
  79545. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79546. this.setRotationQuaternion(quat, space, mesh);
  79547. return;
  79548. }
  79549. var rotMatInv = Bone._tmpMats[0];
  79550. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79551. return;
  79552. }
  79553. var rotMat = Bone._tmpMats[1];
  79554. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79555. rotMatInv.multiplyToRef(rotMat, rotMat);
  79556. this._rotateWithMatrix(rotMat, space, mesh);
  79557. };
  79558. /**
  79559. * Set the euler rotation of the bone in local of world space
  79560. * @param rotation The euler rotation that the bone should be set to
  79561. * @param space The space that the rotation is in
  79562. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79563. */
  79564. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79565. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79566. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79567. };
  79568. /**
  79569. * Set the quaternion rotation of the bone in local of world space
  79570. * @param quat The quaternion rotation that the bone should be set to
  79571. * @param space The space that the rotation is in
  79572. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79573. */
  79574. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79575. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79576. if (space === BABYLON.Space.LOCAL) {
  79577. this._decompose();
  79578. this._localRotation.copyFrom(quat);
  79579. this._markAsDirtyAndCompose();
  79580. return;
  79581. }
  79582. var rotMatInv = Bone._tmpMats[0];
  79583. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79584. return;
  79585. }
  79586. var rotMat = Bone._tmpMats[1];
  79587. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79588. rotMatInv.multiplyToRef(rotMat, rotMat);
  79589. this._rotateWithMatrix(rotMat, space, mesh);
  79590. };
  79591. /**
  79592. * Set the rotation matrix of the bone in local of world space
  79593. * @param rotMat The rotation matrix that the bone should be set to
  79594. * @param space The space that the rotation is in
  79595. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79596. */
  79597. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79598. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79599. if (space === BABYLON.Space.LOCAL) {
  79600. var quat = Bone._tmpQuat;
  79601. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79602. this.setRotationQuaternion(quat, space, mesh);
  79603. return;
  79604. }
  79605. var rotMatInv = Bone._tmpMats[0];
  79606. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79607. return;
  79608. }
  79609. var rotMat2 = Bone._tmpMats[1];
  79610. rotMat2.copyFrom(rotMat);
  79611. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79612. this._rotateWithMatrix(rotMat2, space, mesh);
  79613. };
  79614. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79615. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79616. var lmat = this.getLocalMatrix();
  79617. var lx = lmat.m[12];
  79618. var ly = lmat.m[13];
  79619. var lz = lmat.m[14];
  79620. var parent = this.getParent();
  79621. var parentScale = Bone._tmpMats[3];
  79622. var parentScaleInv = Bone._tmpMats[4];
  79623. if (parent && space == BABYLON.Space.WORLD) {
  79624. if (mesh) {
  79625. parentScale.copyFrom(mesh.getWorldMatrix());
  79626. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79627. }
  79628. else {
  79629. parentScale.copyFrom(parent.getAbsoluteTransform());
  79630. }
  79631. parentScaleInv.copyFrom(parentScale);
  79632. parentScaleInv.invert();
  79633. lmat.multiplyToRef(parentScale, lmat);
  79634. lmat.multiplyToRef(rmat, lmat);
  79635. lmat.multiplyToRef(parentScaleInv, lmat);
  79636. }
  79637. else {
  79638. if (space == BABYLON.Space.WORLD && mesh) {
  79639. parentScale.copyFrom(mesh.getWorldMatrix());
  79640. parentScaleInv.copyFrom(parentScale);
  79641. parentScaleInv.invert();
  79642. lmat.multiplyToRef(parentScale, lmat);
  79643. lmat.multiplyToRef(rmat, lmat);
  79644. lmat.multiplyToRef(parentScaleInv, lmat);
  79645. }
  79646. else {
  79647. lmat.multiplyToRef(rmat, lmat);
  79648. }
  79649. }
  79650. lmat.m[12] = lx;
  79651. lmat.m[13] = ly;
  79652. lmat.m[14] = lz;
  79653. this.computeAbsoluteTransforms();
  79654. this._markAsDirtyAndDecompose();
  79655. };
  79656. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79657. var scaleMatrix = Bone._tmpMats[2];
  79658. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79659. if (mesh) {
  79660. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79661. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79662. }
  79663. rotMatInv.invert();
  79664. if (isNaN(rotMatInv.m[0])) {
  79665. // Matrix failed to invert.
  79666. // This can happen if scale is zero for example.
  79667. return false;
  79668. }
  79669. scaleMatrix.m[0] *= this._scalingDeterminant;
  79670. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79671. return true;
  79672. };
  79673. /**
  79674. * Get the position of the bone in local or world space
  79675. * @param space The space that the returned position is in
  79676. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79677. * @returns The position of the bone
  79678. */
  79679. Bone.prototype.getPosition = function (space, mesh) {
  79680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79681. if (mesh === void 0) { mesh = null; }
  79682. var pos = BABYLON.Vector3.Zero();
  79683. this.getPositionToRef(space, mesh, pos);
  79684. return pos;
  79685. };
  79686. /**
  79687. * Copy the position of the bone to a vector3 in local or world space
  79688. * @param space The space that the returned position is in
  79689. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79690. * @param result The vector3 to copy the position to
  79691. */
  79692. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  79693. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79694. if (space == BABYLON.Space.LOCAL) {
  79695. var lm = this.getLocalMatrix();
  79696. result.x = lm.m[12];
  79697. result.y = lm.m[13];
  79698. result.z = lm.m[14];
  79699. }
  79700. else {
  79701. var wm = null;
  79702. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79703. if (mesh) {
  79704. wm = mesh.getWorldMatrix();
  79705. }
  79706. this._skeleton.computeAbsoluteTransforms();
  79707. var tmat = Bone._tmpMats[0];
  79708. if (mesh && wm) {
  79709. tmat.copyFrom(this.getAbsoluteTransform());
  79710. tmat.multiplyToRef(wm, tmat);
  79711. }
  79712. else {
  79713. tmat = this.getAbsoluteTransform();
  79714. }
  79715. result.x = tmat.m[12];
  79716. result.y = tmat.m[13];
  79717. result.z = tmat.m[14];
  79718. }
  79719. };
  79720. /**
  79721. * Get the absolute position of the bone (world space)
  79722. * @param mesh The mesh that this bone is attached to
  79723. * @returns The absolute position of the bone
  79724. */
  79725. Bone.prototype.getAbsolutePosition = function (mesh) {
  79726. if (mesh === void 0) { mesh = null; }
  79727. var pos = BABYLON.Vector3.Zero();
  79728. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  79729. return pos;
  79730. };
  79731. /**
  79732. * Copy the absolute position of the bone (world space) to the result param
  79733. * @param mesh The mesh that this bone is attached to
  79734. * @param result The vector3 to copy the absolute position to
  79735. */
  79736. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  79737. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  79738. };
  79739. /**
  79740. * Compute the absolute transforms of this bone and its children
  79741. */
  79742. Bone.prototype.computeAbsoluteTransforms = function () {
  79743. this._compose();
  79744. if (this._parent) {
  79745. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79746. }
  79747. else {
  79748. this._absoluteTransform.copyFrom(this._localMatrix);
  79749. var poseMatrix = this._skeleton.getPoseMatrix();
  79750. if (poseMatrix) {
  79751. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  79752. }
  79753. }
  79754. var children = this.children;
  79755. var len = children.length;
  79756. for (var i = 0; i < len; i++) {
  79757. children[i].computeAbsoluteTransforms();
  79758. }
  79759. };
  79760. /**
  79761. * Get the world direction from an axis that is in the local space of the bone
  79762. * @param localAxis The local direction that is used to compute the world direction
  79763. * @param mesh The mesh that this bone is attached to
  79764. * @returns The world direction
  79765. */
  79766. Bone.prototype.getDirection = function (localAxis, mesh) {
  79767. if (mesh === void 0) { mesh = null; }
  79768. var result = BABYLON.Vector3.Zero();
  79769. this.getDirectionToRef(localAxis, mesh, result);
  79770. return result;
  79771. };
  79772. /**
  79773. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  79774. * @param localAxis The local direction that is used to compute the world direction
  79775. * @param mesh The mesh that this bone is attached to
  79776. * @param result The vector3 that the world direction will be copied to
  79777. */
  79778. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  79779. if (mesh === void 0) { mesh = null; }
  79780. var wm = null;
  79781. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79782. if (mesh) {
  79783. wm = mesh.getWorldMatrix();
  79784. }
  79785. this._skeleton.computeAbsoluteTransforms();
  79786. var mat = Bone._tmpMats[0];
  79787. mat.copyFrom(this.getAbsoluteTransform());
  79788. if (mesh && wm) {
  79789. mat.multiplyToRef(wm, mat);
  79790. }
  79791. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  79792. result.normalize();
  79793. };
  79794. /**
  79795. * Get the euler rotation of the bone in local or world space
  79796. * @param space The space that the rotation should be in
  79797. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79798. * @returns The euler rotation
  79799. */
  79800. Bone.prototype.getRotation = function (space, mesh) {
  79801. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79802. if (mesh === void 0) { mesh = null; }
  79803. var result = BABYLON.Vector3.Zero();
  79804. this.getRotationToRef(space, mesh, result);
  79805. return result;
  79806. };
  79807. /**
  79808. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  79809. * @param space The space that the rotation should be in
  79810. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79811. * @param result The vector3 that the rotation should be copied to
  79812. */
  79813. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  79814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79815. if (mesh === void 0) { mesh = null; }
  79816. var quat = Bone._tmpQuat;
  79817. this.getRotationQuaternionToRef(space, mesh, quat);
  79818. quat.toEulerAnglesToRef(result);
  79819. };
  79820. /**
  79821. * Get the quaternion rotation of the bone in either local or world space
  79822. * @param space The space that the rotation should be in
  79823. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79824. * @returns The quaternion rotation
  79825. */
  79826. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  79827. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79828. if (mesh === void 0) { mesh = null; }
  79829. var result = BABYLON.Quaternion.Identity();
  79830. this.getRotationQuaternionToRef(space, mesh, result);
  79831. return result;
  79832. };
  79833. /**
  79834. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  79835. * @param space The space that the rotation should be in
  79836. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79837. * @param result The quaternion that the rotation should be copied to
  79838. */
  79839. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  79840. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79841. if (mesh === void 0) { mesh = null; }
  79842. if (space == BABYLON.Space.LOCAL) {
  79843. this._decompose();
  79844. result.copyFrom(this._localRotation);
  79845. }
  79846. else {
  79847. var mat = Bone._tmpMats[0];
  79848. var amat = this.getAbsoluteTransform();
  79849. if (mesh) {
  79850. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79851. }
  79852. else {
  79853. mat.copyFrom(amat);
  79854. }
  79855. mat.m[0] *= this._scalingDeterminant;
  79856. mat.m[1] *= this._scalingDeterminant;
  79857. mat.m[2] *= this._scalingDeterminant;
  79858. mat.decompose(undefined, result, undefined);
  79859. }
  79860. };
  79861. /**
  79862. * Get the rotation matrix of the bone in local or world space
  79863. * @param space The space that the rotation should be in
  79864. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79865. * @returns The rotation matrix
  79866. */
  79867. Bone.prototype.getRotationMatrix = function (space, mesh) {
  79868. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79869. var result = BABYLON.Matrix.Identity();
  79870. this.getRotationMatrixToRef(space, mesh, result);
  79871. return result;
  79872. };
  79873. /**
  79874. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  79875. * @param space The space that the rotation should be in
  79876. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79877. * @param result The quaternion that the rotation should be copied to
  79878. */
  79879. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  79880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79881. if (space == BABYLON.Space.LOCAL) {
  79882. this.getLocalMatrix().getRotationMatrixToRef(result);
  79883. }
  79884. else {
  79885. var mat = Bone._tmpMats[0];
  79886. var amat = this.getAbsoluteTransform();
  79887. if (mesh) {
  79888. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  79889. }
  79890. else {
  79891. mat.copyFrom(amat);
  79892. }
  79893. mat.m[0] *= this._scalingDeterminant;
  79894. mat.m[1] *= this._scalingDeterminant;
  79895. mat.m[2] *= this._scalingDeterminant;
  79896. mat.getRotationMatrixToRef(result);
  79897. }
  79898. };
  79899. /**
  79900. * Get the world position of a point that is in the local space of the bone
  79901. * @param position The local position
  79902. * @param mesh The mesh that this bone is attached to
  79903. * @returns The world position
  79904. */
  79905. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  79906. if (mesh === void 0) { mesh = null; }
  79907. var result = BABYLON.Vector3.Zero();
  79908. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  79909. return result;
  79910. };
  79911. /**
  79912. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  79913. * @param position The local position
  79914. * @param mesh The mesh that this bone is attached to
  79915. * @param result The vector3 that the world position should be copied to
  79916. */
  79917. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  79918. if (mesh === void 0) { mesh = null; }
  79919. var wm = null;
  79920. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79921. if (mesh) {
  79922. wm = mesh.getWorldMatrix();
  79923. }
  79924. this._skeleton.computeAbsoluteTransforms();
  79925. var tmat = Bone._tmpMats[0];
  79926. if (mesh && wm) {
  79927. tmat.copyFrom(this.getAbsoluteTransform());
  79928. tmat.multiplyToRef(wm, tmat);
  79929. }
  79930. else {
  79931. tmat = this.getAbsoluteTransform();
  79932. }
  79933. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79934. };
  79935. /**
  79936. * Get the local position of a point that is in world space
  79937. * @param position The world position
  79938. * @param mesh The mesh that this bone is attached to
  79939. * @returns The local position
  79940. */
  79941. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  79942. if (mesh === void 0) { mesh = null; }
  79943. var result = BABYLON.Vector3.Zero();
  79944. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  79945. return result;
  79946. };
  79947. /**
  79948. * Get the local position of a point that is in world space and copy it to the result param
  79949. * @param position The world position
  79950. * @param mesh The mesh that this bone is attached to
  79951. * @param result The vector3 that the local position should be copied to
  79952. */
  79953. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  79954. if (mesh === void 0) { mesh = null; }
  79955. var wm = null;
  79956. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79957. if (mesh) {
  79958. wm = mesh.getWorldMatrix();
  79959. }
  79960. this._skeleton.computeAbsoluteTransforms();
  79961. var tmat = Bone._tmpMats[0];
  79962. tmat.copyFrom(this.getAbsoluteTransform());
  79963. if (mesh && wm) {
  79964. tmat.multiplyToRef(wm, tmat);
  79965. }
  79966. tmat.invert();
  79967. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  79968. };
  79969. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  79970. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  79971. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79972. return Bone;
  79973. }(BABYLON.Node));
  79974. BABYLON.Bone = Bone;
  79975. })(BABYLON || (BABYLON = {}));
  79976. //# sourceMappingURL=babylon.bone.js.map
  79977. var BABYLON;
  79978. (function (BABYLON) {
  79979. /**
  79980. * Class used to apply inverse kinematics to bones
  79981. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  79982. */
  79983. var BoneIKController = /** @class */ (function () {
  79984. /**
  79985. * Creates a new BoneIKController
  79986. * @param mesh defines the mesh to control
  79987. * @param bone defines the bone to control
  79988. * @param options defines options to set up the controller
  79989. */
  79990. function BoneIKController(mesh, bone, options) {
  79991. /**
  79992. * Gets or sets the target position
  79993. */
  79994. this.targetPosition = BABYLON.Vector3.Zero();
  79995. /**
  79996. * Gets or sets the pole target position
  79997. */
  79998. this.poleTargetPosition = BABYLON.Vector3.Zero();
  79999. /**
  80000. * Gets or sets the pole target local offset
  80001. */
  80002. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80003. /**
  80004. * Gets or sets the pole angle
  80005. */
  80006. this.poleAngle = 0;
  80007. /**
  80008. * 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)
  80009. */
  80010. this.slerpAmount = 1;
  80011. this._bone1Quat = BABYLON.Quaternion.Identity();
  80012. this._bone1Mat = BABYLON.Matrix.Identity();
  80013. this._bone2Ang = Math.PI;
  80014. this._maxAngle = Math.PI;
  80015. this._rightHandedSystem = false;
  80016. this._bendAxis = BABYLON.Vector3.Right();
  80017. this._slerping = false;
  80018. this._adjustRoll = 0;
  80019. this._bone2 = bone;
  80020. this._bone1 = bone.getParent();
  80021. if (!this._bone1) {
  80022. return;
  80023. }
  80024. this.mesh = mesh;
  80025. var bonePos = bone.getPosition();
  80026. if (bone.getAbsoluteTransform().determinant() > 0) {
  80027. this._rightHandedSystem = true;
  80028. this._bendAxis.x = 0;
  80029. this._bendAxis.y = 0;
  80030. this._bendAxis.z = -1;
  80031. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80032. this._adjustRoll = Math.PI * .5;
  80033. this._bendAxis.z = 1;
  80034. }
  80035. }
  80036. if (this._bone1.length) {
  80037. var boneScale1 = this._bone1.getScale();
  80038. var boneScale2 = this._bone2.getScale();
  80039. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80040. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80041. }
  80042. else if (this._bone1.children[0]) {
  80043. mesh.computeWorldMatrix(true);
  80044. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80045. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80046. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80047. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80048. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80049. }
  80050. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80051. this.maxAngle = Math.PI;
  80052. if (options) {
  80053. if (options.targetMesh) {
  80054. this.targetMesh = options.targetMesh;
  80055. this.targetMesh.computeWorldMatrix(true);
  80056. }
  80057. if (options.poleTargetMesh) {
  80058. this.poleTargetMesh = options.poleTargetMesh;
  80059. this.poleTargetMesh.computeWorldMatrix(true);
  80060. }
  80061. else if (options.poleTargetBone) {
  80062. this.poleTargetBone = options.poleTargetBone;
  80063. }
  80064. else if (this._bone1.getParent()) {
  80065. this.poleTargetBone = this._bone1.getParent();
  80066. }
  80067. if (options.poleTargetLocalOffset) {
  80068. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80069. }
  80070. if (options.poleAngle) {
  80071. this.poleAngle = options.poleAngle;
  80072. }
  80073. if (options.bendAxis) {
  80074. this._bendAxis.copyFrom(options.bendAxis);
  80075. }
  80076. if (options.maxAngle) {
  80077. this.maxAngle = options.maxAngle;
  80078. }
  80079. if (options.slerpAmount) {
  80080. this.slerpAmount = options.slerpAmount;
  80081. }
  80082. }
  80083. }
  80084. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80085. /**
  80086. * Gets or sets maximum allowed angle
  80087. */
  80088. get: function () {
  80089. return this._maxAngle;
  80090. },
  80091. set: function (value) {
  80092. this._setMaxAngle(value);
  80093. },
  80094. enumerable: true,
  80095. configurable: true
  80096. });
  80097. BoneIKController.prototype._setMaxAngle = function (ang) {
  80098. if (ang < 0) {
  80099. ang = 0;
  80100. }
  80101. if (ang > Math.PI || ang == undefined) {
  80102. ang = Math.PI;
  80103. }
  80104. this._maxAngle = ang;
  80105. var a = this._bone1Length;
  80106. var b = this._bone2Length;
  80107. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80108. };
  80109. /**
  80110. * Force the controller to update the bones
  80111. */
  80112. BoneIKController.prototype.update = function () {
  80113. var bone1 = this._bone1;
  80114. if (!bone1) {
  80115. return;
  80116. }
  80117. var target = this.targetPosition;
  80118. var poleTarget = this.poleTargetPosition;
  80119. var mat1 = BoneIKController._tmpMats[0];
  80120. var mat2 = BoneIKController._tmpMats[1];
  80121. if (this.targetMesh) {
  80122. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80123. }
  80124. if (this.poleTargetBone) {
  80125. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80126. }
  80127. else if (this.poleTargetMesh) {
  80128. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80129. }
  80130. var bonePos = BoneIKController._tmpVecs[0];
  80131. var zaxis = BoneIKController._tmpVecs[1];
  80132. var xaxis = BoneIKController._tmpVecs[2];
  80133. var yaxis = BoneIKController._tmpVecs[3];
  80134. var upAxis = BoneIKController._tmpVecs[4];
  80135. var _tmpQuat = BoneIKController._tmpQuat;
  80136. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80137. poleTarget.subtractToRef(bonePos, upAxis);
  80138. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80139. upAxis.y = 1;
  80140. }
  80141. else {
  80142. upAxis.normalize();
  80143. }
  80144. target.subtractToRef(bonePos, yaxis);
  80145. yaxis.normalize();
  80146. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80147. zaxis.normalize();
  80148. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80149. xaxis.normalize();
  80150. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80151. var a = this._bone1Length;
  80152. var b = this._bone2Length;
  80153. var c = BABYLON.Vector3.Distance(bonePos, target);
  80154. if (this._maxReach > 0) {
  80155. c = Math.min(this._maxReach, c);
  80156. }
  80157. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80158. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80159. if (acosa > 1) {
  80160. acosa = 1;
  80161. }
  80162. if (acosb > 1) {
  80163. acosb = 1;
  80164. }
  80165. if (acosa < -1) {
  80166. acosa = -1;
  80167. }
  80168. if (acosb < -1) {
  80169. acosb = -1;
  80170. }
  80171. var angA = Math.acos(acosa);
  80172. var angB = Math.acos(acosb);
  80173. var angC = -angA - angB;
  80174. if (this._rightHandedSystem) {
  80175. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80176. mat2.multiplyToRef(mat1, mat1);
  80177. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80178. mat2.multiplyToRef(mat1, mat1);
  80179. }
  80180. else {
  80181. var _tmpVec = BoneIKController._tmpVecs[5];
  80182. _tmpVec.copyFrom(this._bendAxis);
  80183. _tmpVec.x *= -1;
  80184. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80185. mat2.multiplyToRef(mat1, mat1);
  80186. }
  80187. if (this.poleAngle) {
  80188. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80189. mat1.multiplyToRef(mat2, mat1);
  80190. }
  80191. if (this._bone1) {
  80192. if (this.slerpAmount < 1) {
  80193. if (!this._slerping) {
  80194. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80195. }
  80196. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80197. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80198. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80199. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80200. this._slerping = true;
  80201. }
  80202. else {
  80203. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80204. this._bone1Mat.copyFrom(mat1);
  80205. this._slerping = false;
  80206. }
  80207. }
  80208. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80209. this._bone2Ang = angC;
  80210. };
  80211. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80212. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80213. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80214. return BoneIKController;
  80215. }());
  80216. BABYLON.BoneIKController = BoneIKController;
  80217. })(BABYLON || (BABYLON = {}));
  80218. //# sourceMappingURL=babylon.boneIKController.js.map
  80219. var BABYLON;
  80220. (function (BABYLON) {
  80221. /**
  80222. * Class used to make a bone look toward a point in space
  80223. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80224. */
  80225. var BoneLookController = /** @class */ (function () {
  80226. /**
  80227. * Create a BoneLookController
  80228. * @param mesh the mesh that the bone belongs to
  80229. * @param bone the bone that will be looking to the target
  80230. * @param target the target Vector3 to look at
  80231. * @param settings optional settings:
  80232. * * maxYaw: the maximum angle the bone will yaw to
  80233. * * minYaw: the minimum angle the bone will yaw to
  80234. * * maxPitch: the maximum angle the bone will pitch to
  80235. * * minPitch: the minimum angle the bone will yaw to
  80236. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80237. * * upAxis: the up axis of the coordinate system
  80238. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80239. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80240. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80241. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80242. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80243. * * adjustRoll: used to make an adjustment to the roll of the bone
  80244. **/
  80245. function BoneLookController(mesh, bone, target, options) {
  80246. /**
  80247. * The up axis of the coordinate system that is used when the bone is rotated
  80248. */
  80249. this.upAxis = BABYLON.Vector3.Up();
  80250. /**
  80251. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80252. */
  80253. this.upAxisSpace = BABYLON.Space.LOCAL;
  80254. /**
  80255. * Used to make an adjustment to the yaw of the bone
  80256. */
  80257. this.adjustYaw = 0;
  80258. /**
  80259. * Used to make an adjustment to the pitch of the bone
  80260. */
  80261. this.adjustPitch = 0;
  80262. /**
  80263. * Used to make an adjustment to the roll of the bone
  80264. */
  80265. this.adjustRoll = 0;
  80266. /**
  80267. * 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)
  80268. */
  80269. this.slerpAmount = 1;
  80270. this._boneQuat = BABYLON.Quaternion.Identity();
  80271. this._slerping = false;
  80272. this._firstFrameSkipped = false;
  80273. this._fowardAxis = BABYLON.Vector3.Forward();
  80274. this.mesh = mesh;
  80275. this.bone = bone;
  80276. this.target = target;
  80277. if (options) {
  80278. if (options.adjustYaw) {
  80279. this.adjustYaw = options.adjustYaw;
  80280. }
  80281. if (options.adjustPitch) {
  80282. this.adjustPitch = options.adjustPitch;
  80283. }
  80284. if (options.adjustRoll) {
  80285. this.adjustRoll = options.adjustRoll;
  80286. }
  80287. if (options.maxYaw != null) {
  80288. this.maxYaw = options.maxYaw;
  80289. }
  80290. else {
  80291. this.maxYaw = Math.PI;
  80292. }
  80293. if (options.minYaw != null) {
  80294. this.minYaw = options.minYaw;
  80295. }
  80296. else {
  80297. this.minYaw = -Math.PI;
  80298. }
  80299. if (options.maxPitch != null) {
  80300. this.maxPitch = options.maxPitch;
  80301. }
  80302. else {
  80303. this.maxPitch = Math.PI;
  80304. }
  80305. if (options.minPitch != null) {
  80306. this.minPitch = options.minPitch;
  80307. }
  80308. else {
  80309. this.minPitch = -Math.PI;
  80310. }
  80311. if (options.slerpAmount != null) {
  80312. this.slerpAmount = options.slerpAmount;
  80313. }
  80314. if (options.upAxis != null) {
  80315. this.upAxis = options.upAxis;
  80316. }
  80317. if (options.upAxisSpace != null) {
  80318. this.upAxisSpace = options.upAxisSpace;
  80319. }
  80320. if (options.yawAxis != null || options.pitchAxis != null) {
  80321. var newYawAxis = BABYLON.Axis.Y;
  80322. var newPitchAxis = BABYLON.Axis.X;
  80323. if (options.yawAxis != null) {
  80324. newYawAxis = options.yawAxis.clone();
  80325. newYawAxis.normalize();
  80326. }
  80327. if (options.pitchAxis != null) {
  80328. newPitchAxis = options.pitchAxis.clone();
  80329. newPitchAxis.normalize();
  80330. }
  80331. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80332. this._transformYawPitch = BABYLON.Matrix.Identity();
  80333. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80334. this._transformYawPitchInv = this._transformYawPitch.clone();
  80335. this._transformYawPitch.invert();
  80336. }
  80337. }
  80338. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80339. this.upAxisSpace = BABYLON.Space.LOCAL;
  80340. }
  80341. }
  80342. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80343. /**
  80344. * Gets or sets the minimum yaw angle that the bone can look to
  80345. */
  80346. get: function () {
  80347. return this._minYaw;
  80348. },
  80349. set: function (value) {
  80350. this._minYaw = value;
  80351. this._minYawSin = Math.sin(value);
  80352. this._minYawCos = Math.cos(value);
  80353. if (this._maxYaw != null) {
  80354. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80355. this._yawRange = this._maxYaw - this._minYaw;
  80356. }
  80357. },
  80358. enumerable: true,
  80359. configurable: true
  80360. });
  80361. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80362. /**
  80363. * Gets or sets the maximum yaw angle that the bone can look to
  80364. */
  80365. get: function () {
  80366. return this._maxYaw;
  80367. },
  80368. set: function (value) {
  80369. this._maxYaw = value;
  80370. this._maxYawSin = Math.sin(value);
  80371. this._maxYawCos = Math.cos(value);
  80372. if (this._minYaw != null) {
  80373. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80374. this._yawRange = this._maxYaw - this._minYaw;
  80375. }
  80376. },
  80377. enumerable: true,
  80378. configurable: true
  80379. });
  80380. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80381. /**
  80382. * Gets or sets the minimum pitch angle that the bone can look to
  80383. */
  80384. get: function () {
  80385. return this._minPitch;
  80386. },
  80387. set: function (value) {
  80388. this._minPitch = value;
  80389. this._minPitchTan = Math.tan(value);
  80390. },
  80391. enumerable: true,
  80392. configurable: true
  80393. });
  80394. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80395. /**
  80396. * Gets or sets the maximum pitch angle that the bone can look to
  80397. */
  80398. get: function () {
  80399. return this._maxPitch;
  80400. },
  80401. set: function (value) {
  80402. this._maxPitch = value;
  80403. this._maxPitchTan = Math.tan(value);
  80404. },
  80405. enumerable: true,
  80406. configurable: true
  80407. });
  80408. /**
  80409. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80410. */
  80411. BoneLookController.prototype.update = function () {
  80412. //skip the first frame when slerping so that the mesh rotation is correct
  80413. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80414. this._firstFrameSkipped = true;
  80415. return;
  80416. }
  80417. var bone = this.bone;
  80418. var bonePos = BoneLookController._tmpVecs[0];
  80419. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80420. var target = this.target;
  80421. var _tmpMat1 = BoneLookController._tmpMats[0];
  80422. var _tmpMat2 = BoneLookController._tmpMats[1];
  80423. var mesh = this.mesh;
  80424. var parentBone = bone.getParent();
  80425. var upAxis = BoneLookController._tmpVecs[1];
  80426. upAxis.copyFrom(this.upAxis);
  80427. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80428. if (this._transformYawPitch) {
  80429. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80430. }
  80431. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80432. }
  80433. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80434. mesh.getDirectionToRef(upAxis, upAxis);
  80435. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80436. upAxis.normalize();
  80437. }
  80438. }
  80439. var checkYaw = false;
  80440. var checkPitch = false;
  80441. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80442. checkYaw = true;
  80443. }
  80444. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80445. checkPitch = true;
  80446. }
  80447. if (checkYaw || checkPitch) {
  80448. var spaceMat = BoneLookController._tmpMats[2];
  80449. var spaceMatInv = BoneLookController._tmpMats[3];
  80450. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80451. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80452. }
  80453. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80454. spaceMat.copyFrom(mesh.getWorldMatrix());
  80455. }
  80456. else {
  80457. var forwardAxis = BoneLookController._tmpVecs[2];
  80458. forwardAxis.copyFrom(this._fowardAxis);
  80459. if (this._transformYawPitch) {
  80460. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80461. }
  80462. if (parentBone) {
  80463. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80464. }
  80465. else {
  80466. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80467. }
  80468. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80469. rightAxis.normalize();
  80470. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80471. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80472. }
  80473. spaceMat.invertToRef(spaceMatInv);
  80474. var xzlen = null;
  80475. if (checkPitch) {
  80476. var localTarget = BoneLookController._tmpVecs[3];
  80477. target.subtractToRef(bonePos, localTarget);
  80478. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80479. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80480. var pitch = Math.atan2(localTarget.y, xzlen);
  80481. var newPitch = pitch;
  80482. if (pitch > this._maxPitch) {
  80483. localTarget.y = this._maxPitchTan * xzlen;
  80484. newPitch = this._maxPitch;
  80485. }
  80486. else if (pitch < this._minPitch) {
  80487. localTarget.y = this._minPitchTan * xzlen;
  80488. newPitch = this._minPitch;
  80489. }
  80490. if (pitch != newPitch) {
  80491. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80492. localTarget.addInPlace(bonePos);
  80493. target = localTarget;
  80494. }
  80495. }
  80496. if (checkYaw) {
  80497. var localTarget = BoneLookController._tmpVecs[4];
  80498. target.subtractToRef(bonePos, localTarget);
  80499. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80500. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80501. var newYaw = yaw;
  80502. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80503. if (xzlen == null) {
  80504. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80505. }
  80506. if (this._yawRange > Math.PI) {
  80507. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80508. localTarget.z = this._maxYawCos * xzlen;
  80509. localTarget.x = this._maxYawSin * xzlen;
  80510. newYaw = this._maxYaw;
  80511. }
  80512. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80513. localTarget.z = this._minYawCos * xzlen;
  80514. localTarget.x = this._minYawSin * xzlen;
  80515. newYaw = this._minYaw;
  80516. }
  80517. }
  80518. else {
  80519. if (yaw > this._maxYaw) {
  80520. localTarget.z = this._maxYawCos * xzlen;
  80521. localTarget.x = this._maxYawSin * xzlen;
  80522. newYaw = this._maxYaw;
  80523. }
  80524. else if (yaw < this._minYaw) {
  80525. localTarget.z = this._minYawCos * xzlen;
  80526. localTarget.x = this._minYawSin * xzlen;
  80527. newYaw = this._minYaw;
  80528. }
  80529. }
  80530. }
  80531. if (this._slerping && this._yawRange > Math.PI) {
  80532. //are we going to be crossing into the min/max region?
  80533. var boneFwd = BoneLookController._tmpVecs[8];
  80534. boneFwd.copyFrom(BABYLON.Axis.Z);
  80535. if (this._transformYawPitch) {
  80536. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80537. }
  80538. var boneRotMat = BoneLookController._tmpMats[4];
  80539. this._boneQuat.toRotationMatrix(boneRotMat);
  80540. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80541. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80542. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80543. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80544. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80545. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80546. if (angBtwTar > angBtwMidYaw) {
  80547. if (xzlen == null) {
  80548. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80549. }
  80550. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80551. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80552. if (angBtwMin < angBtwMax) {
  80553. newYaw = boneYaw + Math.PI * .75;
  80554. localTarget.z = Math.cos(newYaw) * xzlen;
  80555. localTarget.x = Math.sin(newYaw) * xzlen;
  80556. }
  80557. else {
  80558. newYaw = boneYaw - Math.PI * .75;
  80559. localTarget.z = Math.cos(newYaw) * xzlen;
  80560. localTarget.x = Math.sin(newYaw) * xzlen;
  80561. }
  80562. }
  80563. }
  80564. if (yaw != newYaw) {
  80565. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80566. localTarget.addInPlace(bonePos);
  80567. target = localTarget;
  80568. }
  80569. }
  80570. }
  80571. var zaxis = BoneLookController._tmpVecs[5];
  80572. var xaxis = BoneLookController._tmpVecs[6];
  80573. var yaxis = BoneLookController._tmpVecs[7];
  80574. var _tmpQuat = BoneLookController._tmpQuat;
  80575. target.subtractToRef(bonePos, zaxis);
  80576. zaxis.normalize();
  80577. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80578. xaxis.normalize();
  80579. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80580. yaxis.normalize();
  80581. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80582. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80583. return;
  80584. }
  80585. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80586. return;
  80587. }
  80588. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80589. return;
  80590. }
  80591. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80592. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80593. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80594. }
  80595. if (this.slerpAmount < 1) {
  80596. if (!this._slerping) {
  80597. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80598. }
  80599. if (this._transformYawPitch) {
  80600. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80601. }
  80602. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80603. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80604. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80605. this._slerping = true;
  80606. }
  80607. else {
  80608. if (this._transformYawPitch) {
  80609. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80610. }
  80611. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80612. this._slerping = false;
  80613. }
  80614. };
  80615. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80616. var angDiff = ang2 - ang1;
  80617. angDiff %= Math.PI * 2;
  80618. if (angDiff > Math.PI) {
  80619. angDiff -= Math.PI * 2;
  80620. }
  80621. else if (angDiff < -Math.PI) {
  80622. angDiff += Math.PI * 2;
  80623. }
  80624. return angDiff;
  80625. };
  80626. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80627. ang1 %= (2 * Math.PI);
  80628. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80629. ang2 %= (2 * Math.PI);
  80630. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80631. var ab = 0;
  80632. if (ang1 < ang2) {
  80633. ab = ang2 - ang1;
  80634. }
  80635. else {
  80636. ab = ang1 - ang2;
  80637. }
  80638. if (ab > Math.PI) {
  80639. ab = Math.PI * 2 - ab;
  80640. }
  80641. return ab;
  80642. };
  80643. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80644. ang %= (2 * Math.PI);
  80645. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80646. ang1 %= (2 * Math.PI);
  80647. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80648. ang2 %= (2 * Math.PI);
  80649. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80650. if (ang1 < ang2) {
  80651. if (ang > ang1 && ang < ang2) {
  80652. return true;
  80653. }
  80654. }
  80655. else {
  80656. if (ang > ang2 && ang < ang1) {
  80657. return true;
  80658. }
  80659. }
  80660. return false;
  80661. };
  80662. 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()];
  80663. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80664. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80665. return BoneLookController;
  80666. }());
  80667. BABYLON.BoneLookController = BoneLookController;
  80668. })(BABYLON || (BABYLON = {}));
  80669. //# sourceMappingURL=babylon.boneLookController.js.map
  80670. var BABYLON;
  80671. (function (BABYLON) {
  80672. /**
  80673. * Class used to handle skinning animations
  80674. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80675. */
  80676. var Skeleton = /** @class */ (function () {
  80677. /**
  80678. * Creates a new skeleton
  80679. * @param name defines the skeleton name
  80680. * @param id defines the skeleton Id
  80681. * @param scene defines the hosting scene
  80682. */
  80683. function Skeleton(
  80684. /** defines the skeleton name */
  80685. name,
  80686. /** defines the skeleton Id */
  80687. id, scene) {
  80688. this.name = name;
  80689. this.id = id;
  80690. /**
  80691. * Gets the list of child bones
  80692. */
  80693. this.bones = new Array();
  80694. /**
  80695. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  80696. */
  80697. this.needInitialSkinMatrix = false;
  80698. this._isDirty = true;
  80699. this._meshesWithPoseMatrix = new Array();
  80700. this._identity = BABYLON.Matrix.Identity();
  80701. this._ranges = {};
  80702. this._lastAbsoluteTransformsUpdateId = -1;
  80703. /**
  80704. * Specifies if the skeleton should be serialized
  80705. */
  80706. this.doNotSerialize = false;
  80707. this._animationPropertiesOverride = null;
  80708. // Events
  80709. /**
  80710. * An observable triggered before computing the skeleton's matrices
  80711. */
  80712. this.onBeforeComputeObservable = new BABYLON.Observable();
  80713. this.bones = [];
  80714. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80715. scene.skeletons.push(this);
  80716. //make sure it will recalculate the matrix next time prepare is called.
  80717. this._isDirty = true;
  80718. }
  80719. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  80720. /**
  80721. * Gets or sets the animation properties override
  80722. */
  80723. get: function () {
  80724. if (!this._animationPropertiesOverride) {
  80725. return this._scene.animationPropertiesOverride;
  80726. }
  80727. return this._animationPropertiesOverride;
  80728. },
  80729. set: function (value) {
  80730. this._animationPropertiesOverride = value;
  80731. },
  80732. enumerable: true,
  80733. configurable: true
  80734. });
  80735. // Members
  80736. /**
  80737. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  80738. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  80739. * @returns a Float32Array containing matrices data
  80740. */
  80741. Skeleton.prototype.getTransformMatrices = function (mesh) {
  80742. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  80743. return mesh._bonesTransformMatrices;
  80744. }
  80745. if (!this._transformMatrices) {
  80746. this.prepare();
  80747. }
  80748. return this._transformMatrices;
  80749. };
  80750. /**
  80751. * Gets the current hosting scene
  80752. * @returns a scene object
  80753. */
  80754. Skeleton.prototype.getScene = function () {
  80755. return this._scene;
  80756. };
  80757. // Methods
  80758. /**
  80759. * Gets a string representing the current skeleton data
  80760. * @param fullDetails defines a boolean indicating if we want a verbose version
  80761. * @returns a string representing the current skeleton data
  80762. */
  80763. Skeleton.prototype.toString = function (fullDetails) {
  80764. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  80765. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  80766. if (fullDetails) {
  80767. ret += ", Ranges: {";
  80768. var first = true;
  80769. for (var name_1 in this._ranges) {
  80770. if (first) {
  80771. ret += ", ";
  80772. first = false;
  80773. }
  80774. ret += name_1;
  80775. }
  80776. ret += "}";
  80777. }
  80778. return ret;
  80779. };
  80780. /**
  80781. * Get bone's index searching by name
  80782. * @param name defines bone's name to search for
  80783. * @return the indice of the bone. Returns -1 if not found
  80784. */
  80785. Skeleton.prototype.getBoneIndexByName = function (name) {
  80786. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  80787. if (this.bones[boneIndex].name === name) {
  80788. return boneIndex;
  80789. }
  80790. }
  80791. return -1;
  80792. };
  80793. /**
  80794. * Creater a new animation range
  80795. * @param name defines the name of the range
  80796. * @param from defines the start key
  80797. * @param to defines the end key
  80798. */
  80799. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  80800. // check name not already in use
  80801. if (!this._ranges[name]) {
  80802. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  80803. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80804. if (this.bones[i].animations[0]) {
  80805. this.bones[i].animations[0].createRange(name, from, to);
  80806. }
  80807. }
  80808. }
  80809. };
  80810. /**
  80811. * Delete a specific animation range
  80812. * @param name defines the name of the range
  80813. * @param deleteFrames defines if frames must be removed as well
  80814. */
  80815. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  80816. if (deleteFrames === void 0) { deleteFrames = true; }
  80817. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80818. if (this.bones[i].animations[0]) {
  80819. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  80820. }
  80821. }
  80822. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  80823. };
  80824. /**
  80825. * Gets a specific animation range
  80826. * @param name defines the name of the range to look for
  80827. * @returns the requested animation range or null if not found
  80828. */
  80829. Skeleton.prototype.getAnimationRange = function (name) {
  80830. return this._ranges[name];
  80831. };
  80832. /**
  80833. * Gets the list of all animation ranges defined on this skeleton
  80834. * @returns an array
  80835. */
  80836. Skeleton.prototype.getAnimationRanges = function () {
  80837. var animationRanges = [];
  80838. var name;
  80839. var i = 0;
  80840. for (name in this._ranges) {
  80841. animationRanges[i] = this._ranges[name];
  80842. i++;
  80843. }
  80844. return animationRanges;
  80845. };
  80846. /**
  80847. * Copy animation range from a source skeleton.
  80848. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  80849. * @param source defines the source skeleton
  80850. * @param name defines the name of the range to copy
  80851. * @param rescaleAsRequired defines if rescaling must be applied if required
  80852. * @returns true if operation was successful
  80853. */
  80854. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  80855. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  80856. if (this._ranges[name] || !source.getAnimationRange(name)) {
  80857. return false;
  80858. }
  80859. var ret = true;
  80860. var frameOffset = this._getHighestAnimationFrame() + 1;
  80861. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  80862. var boneDict = {};
  80863. var sourceBones = source.bones;
  80864. var nBones;
  80865. var i;
  80866. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  80867. boneDict[sourceBones[i].name] = sourceBones[i];
  80868. }
  80869. if (this.bones.length !== sourceBones.length) {
  80870. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  80871. ret = false;
  80872. }
  80873. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  80874. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  80875. var boneName = this.bones[i].name;
  80876. var sourceBone = boneDict[boneName];
  80877. if (sourceBone) {
  80878. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  80879. }
  80880. else {
  80881. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  80882. ret = false;
  80883. }
  80884. }
  80885. // do not call createAnimationRange(), since it also is done to bones, which was already done
  80886. var range = source.getAnimationRange(name);
  80887. if (range) {
  80888. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  80889. }
  80890. return ret;
  80891. };
  80892. /**
  80893. * Forces the skeleton to go to rest pose
  80894. */
  80895. Skeleton.prototype.returnToRest = function () {
  80896. for (var index = 0; index < this.bones.length; index++) {
  80897. this.bones[index].returnToRest();
  80898. }
  80899. };
  80900. Skeleton.prototype._getHighestAnimationFrame = function () {
  80901. var ret = 0;
  80902. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  80903. if (this.bones[i].animations[0]) {
  80904. var highest = this.bones[i].animations[0].getHighestFrame();
  80905. if (ret < highest) {
  80906. ret = highest;
  80907. }
  80908. }
  80909. }
  80910. return ret;
  80911. };
  80912. /**
  80913. * Begin a specific animation range
  80914. * @param name defines the name of the range to start
  80915. * @param loop defines if looping must be turned on (false by default)
  80916. * @param speedRatio defines the speed ratio to apply (1 by default)
  80917. * @param onAnimationEnd defines a callback which will be called when animation will end
  80918. * @returns a new animatable
  80919. */
  80920. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  80921. var range = this.getAnimationRange(name);
  80922. if (!range) {
  80923. return null;
  80924. }
  80925. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  80926. };
  80927. /** @hidden */
  80928. Skeleton.prototype._markAsDirty = function () {
  80929. this._isDirty = true;
  80930. };
  80931. /** @hidden */
  80932. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  80933. this._meshesWithPoseMatrix.push(mesh);
  80934. };
  80935. /** @hidden */
  80936. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  80937. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  80938. if (index > -1) {
  80939. this._meshesWithPoseMatrix.splice(index, 1);
  80940. }
  80941. };
  80942. /** @hidden */
  80943. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  80944. this.onBeforeComputeObservable.notifyObservers(this);
  80945. for (var index = 0; index < this.bones.length; index++) {
  80946. var bone = this.bones[index];
  80947. var parentBone = bone.getParent();
  80948. if (parentBone) {
  80949. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  80950. }
  80951. else {
  80952. if (initialSkinMatrix) {
  80953. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  80954. }
  80955. else {
  80956. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  80957. }
  80958. }
  80959. if (bone._index !== -1) {
  80960. var mappedIndex = bone._index === null ? index : bone._index;
  80961. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  80962. }
  80963. }
  80964. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  80965. };
  80966. /**
  80967. * Build all resources required to render a skeleton
  80968. */
  80969. Skeleton.prototype.prepare = function () {
  80970. if (!this._isDirty) {
  80971. return;
  80972. }
  80973. if (this.needInitialSkinMatrix) {
  80974. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  80975. var mesh = this._meshesWithPoseMatrix[index];
  80976. var poseMatrix = mesh.getPoseMatrix();
  80977. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  80978. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80979. }
  80980. if (this._synchronizedWithMesh !== mesh) {
  80981. this._synchronizedWithMesh = mesh;
  80982. // Prepare bones
  80983. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  80984. var bone = this.bones[boneIndex];
  80985. if (!bone.getParent()) {
  80986. var matrix = bone.getBaseMatrix();
  80987. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  80988. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  80989. }
  80990. }
  80991. }
  80992. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  80993. }
  80994. }
  80995. else {
  80996. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  80997. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  80998. }
  80999. this._computeTransformMatrices(this._transformMatrices, null);
  81000. }
  81001. this._isDirty = false;
  81002. this._scene._activeBones.addCount(this.bones.length, false);
  81003. };
  81004. /**
  81005. * Gets the list of animatables currently running for this skeleton
  81006. * @returns an array of animatables
  81007. */
  81008. Skeleton.prototype.getAnimatables = function () {
  81009. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81010. this._animatables = [];
  81011. for (var index = 0; index < this.bones.length; index++) {
  81012. this._animatables.push(this.bones[index]);
  81013. }
  81014. }
  81015. return this._animatables;
  81016. };
  81017. /**
  81018. * Clone the current skeleton
  81019. * @param name defines the name of the new skeleton
  81020. * @param id defines the id of the enw skeleton
  81021. * @returns the new skeleton
  81022. */
  81023. Skeleton.prototype.clone = function (name, id) {
  81024. var result = new Skeleton(name, id || name, this._scene);
  81025. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81026. for (var index = 0; index < this.bones.length; index++) {
  81027. var source = this.bones[index];
  81028. var parentBone = null;
  81029. var parent_1 = source.getParent();
  81030. if (parent_1) {
  81031. var parentIndex = this.bones.indexOf(parent_1);
  81032. parentBone = result.bones[parentIndex];
  81033. }
  81034. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81035. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81036. }
  81037. if (this._ranges) {
  81038. result._ranges = {};
  81039. for (var rangeName in this._ranges) {
  81040. var range = this._ranges[rangeName];
  81041. if (range) {
  81042. result._ranges[rangeName] = range.clone();
  81043. }
  81044. }
  81045. }
  81046. this._isDirty = true;
  81047. return result;
  81048. };
  81049. /**
  81050. * Enable animation blending for this skeleton
  81051. * @param blendingSpeed defines the blending speed to apply
  81052. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81053. */
  81054. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81055. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81056. this.bones.forEach(function (bone) {
  81057. bone.animations.forEach(function (animation) {
  81058. animation.enableBlending = true;
  81059. animation.blendingSpeed = blendingSpeed;
  81060. });
  81061. });
  81062. };
  81063. /**
  81064. * Releases all resources associated with the current skeleton
  81065. */
  81066. Skeleton.prototype.dispose = function () {
  81067. this._meshesWithPoseMatrix = [];
  81068. // Animations
  81069. this.getScene().stopAnimation(this);
  81070. // Remove from scene
  81071. this.getScene().removeSkeleton(this);
  81072. };
  81073. /**
  81074. * Serialize the skeleton in a JSON object
  81075. * @returns a JSON object
  81076. */
  81077. Skeleton.prototype.serialize = function () {
  81078. var serializationObject = {};
  81079. serializationObject.name = this.name;
  81080. serializationObject.id = this.id;
  81081. if (this.dimensionsAtRest) {
  81082. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81083. }
  81084. serializationObject.bones = [];
  81085. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81086. for (var index = 0; index < this.bones.length; index++) {
  81087. var bone = this.bones[index];
  81088. var parent_2 = bone.getParent();
  81089. var serializedBone = {
  81090. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81091. name: bone.name,
  81092. matrix: bone.getBaseMatrix().toArray(),
  81093. rest: bone.getRestPose().toArray()
  81094. };
  81095. serializationObject.bones.push(serializedBone);
  81096. if (bone.length) {
  81097. serializedBone.length = bone.length;
  81098. }
  81099. if (bone.metadata) {
  81100. serializedBone.metadata = bone.metadata;
  81101. }
  81102. if (bone.animations && bone.animations.length > 0) {
  81103. serializedBone.animation = bone.animations[0].serialize();
  81104. }
  81105. serializationObject.ranges = [];
  81106. for (var name in this._ranges) {
  81107. var source = this._ranges[name];
  81108. if (!source) {
  81109. continue;
  81110. }
  81111. var range = {};
  81112. range.name = name;
  81113. range.from = source.from;
  81114. range.to = source.to;
  81115. serializationObject.ranges.push(range);
  81116. }
  81117. }
  81118. return serializationObject;
  81119. };
  81120. /**
  81121. * Creates a new skeleton from serialized data
  81122. * @param parsedSkeleton defines the serialized data
  81123. * @param scene defines the hosting scene
  81124. * @returns a new skeleton
  81125. */
  81126. Skeleton.Parse = function (parsedSkeleton, scene) {
  81127. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81128. if (parsedSkeleton.dimensionsAtRest) {
  81129. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81130. }
  81131. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81132. var index;
  81133. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81134. var parsedBone = parsedSkeleton.bones[index];
  81135. var parentBone = null;
  81136. if (parsedBone.parentBoneIndex > -1) {
  81137. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81138. }
  81139. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81140. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81141. if (parsedBone.length) {
  81142. bone.length = parsedBone.length;
  81143. }
  81144. if (parsedBone.metadata) {
  81145. bone.metadata = parsedBone.metadata;
  81146. }
  81147. if (parsedBone.animation) {
  81148. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81149. }
  81150. }
  81151. // placed after bones, so createAnimationRange can cascade down
  81152. if (parsedSkeleton.ranges) {
  81153. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81154. var data = parsedSkeleton.ranges[index];
  81155. skeleton.createAnimationRange(data.name, data.from, data.to);
  81156. }
  81157. }
  81158. return skeleton;
  81159. };
  81160. /**
  81161. * Compute all node absolute transforms
  81162. * @param forceUpdate defines if computation must be done even if cache is up to date
  81163. */
  81164. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81165. if (forceUpdate === void 0) { forceUpdate = false; }
  81166. var renderId = this._scene.getRenderId();
  81167. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81168. this.bones[0].computeAbsoluteTransforms();
  81169. this._lastAbsoluteTransformsUpdateId = renderId;
  81170. }
  81171. };
  81172. /**
  81173. * Gets the root pose matrix
  81174. * @returns a matrix
  81175. */
  81176. Skeleton.prototype.getPoseMatrix = function () {
  81177. var poseMatrix = null;
  81178. if (this._meshesWithPoseMatrix.length > 0) {
  81179. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81180. }
  81181. return poseMatrix;
  81182. };
  81183. /**
  81184. * Sorts bones per internal index
  81185. */
  81186. Skeleton.prototype.sortBones = function () {
  81187. var bones = new Array();
  81188. var visited = new Array(this.bones.length);
  81189. for (var index = 0; index < this.bones.length; index++) {
  81190. this._sortBones(index, bones, visited);
  81191. }
  81192. this.bones = bones;
  81193. };
  81194. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81195. if (visited[index]) {
  81196. return;
  81197. }
  81198. visited[index] = true;
  81199. var bone = this.bones[index];
  81200. if (bone._index === undefined) {
  81201. bone._index = index;
  81202. }
  81203. var parentBone = bone.getParent();
  81204. if (parentBone) {
  81205. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81206. }
  81207. bones.push(bone);
  81208. };
  81209. return Skeleton;
  81210. }());
  81211. BABYLON.Skeleton = Skeleton;
  81212. })(BABYLON || (BABYLON = {}));
  81213. //# sourceMappingURL=babylon.skeleton.js.map
  81214. var BABYLON;
  81215. (function (BABYLON) {
  81216. var SphericalPolynomial = /** @class */ (function () {
  81217. function SphericalPolynomial() {
  81218. this.x = BABYLON.Vector3.Zero();
  81219. this.y = BABYLON.Vector3.Zero();
  81220. this.z = BABYLON.Vector3.Zero();
  81221. this.xx = BABYLON.Vector3.Zero();
  81222. this.yy = BABYLON.Vector3.Zero();
  81223. this.zz = BABYLON.Vector3.Zero();
  81224. this.xy = BABYLON.Vector3.Zero();
  81225. this.yz = BABYLON.Vector3.Zero();
  81226. this.zx = BABYLON.Vector3.Zero();
  81227. }
  81228. SphericalPolynomial.prototype.addAmbient = function (color) {
  81229. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81230. this.xx = this.xx.add(colorVector);
  81231. this.yy = this.yy.add(colorVector);
  81232. this.zz = this.zz.add(colorVector);
  81233. };
  81234. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81235. var result = new SphericalPolynomial();
  81236. result.x = harmonics.L11.scale(1.02333);
  81237. result.y = harmonics.L1_1.scale(1.02333);
  81238. result.z = harmonics.L10.scale(1.02333);
  81239. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81240. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81241. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81242. result.yz = harmonics.L2_1.scale(0.858086);
  81243. result.zx = harmonics.L21.scale(0.858086);
  81244. result.xy = harmonics.L2_2.scale(0.858086);
  81245. result.scale(1.0 / Math.PI);
  81246. return result;
  81247. };
  81248. SphericalPolynomial.prototype.scale = function (scale) {
  81249. this.x = this.x.scale(scale);
  81250. this.y = this.y.scale(scale);
  81251. this.z = this.z.scale(scale);
  81252. this.xx = this.xx.scale(scale);
  81253. this.yy = this.yy.scale(scale);
  81254. this.zz = this.zz.scale(scale);
  81255. this.yz = this.yz.scale(scale);
  81256. this.zx = this.zx.scale(scale);
  81257. this.xy = this.xy.scale(scale);
  81258. };
  81259. return SphericalPolynomial;
  81260. }());
  81261. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81262. var SphericalHarmonics = /** @class */ (function () {
  81263. function SphericalHarmonics() {
  81264. this.L00 = BABYLON.Vector3.Zero();
  81265. this.L1_1 = BABYLON.Vector3.Zero();
  81266. this.L10 = BABYLON.Vector3.Zero();
  81267. this.L11 = BABYLON.Vector3.Zero();
  81268. this.L2_2 = BABYLON.Vector3.Zero();
  81269. this.L2_1 = BABYLON.Vector3.Zero();
  81270. this.L20 = BABYLON.Vector3.Zero();
  81271. this.L21 = BABYLON.Vector3.Zero();
  81272. this.L22 = BABYLON.Vector3.Zero();
  81273. }
  81274. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81275. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81276. var c = colorVector.scale(deltaSolidAngle);
  81277. this.L00 = this.L00.add(c.scale(0.282095));
  81278. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81279. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81280. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81281. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81282. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81283. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81284. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81285. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81286. };
  81287. SphericalHarmonics.prototype.scale = function (scale) {
  81288. this.L00 = this.L00.scale(scale);
  81289. this.L1_1 = this.L1_1.scale(scale);
  81290. this.L10 = this.L10.scale(scale);
  81291. this.L11 = this.L11.scale(scale);
  81292. this.L2_2 = this.L2_2.scale(scale);
  81293. this.L2_1 = this.L2_1.scale(scale);
  81294. this.L20 = this.L20.scale(scale);
  81295. this.L21 = this.L21.scale(scale);
  81296. this.L22 = this.L22.scale(scale);
  81297. };
  81298. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81299. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81300. //
  81301. // E_lm = A_l * L_lm
  81302. //
  81303. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81304. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81305. // the scaling factors are given in equation 9.
  81306. // Constant (Band 0)
  81307. this.L00 = this.L00.scale(3.141593);
  81308. // Linear (Band 1)
  81309. this.L1_1 = this.L1_1.scale(2.094395);
  81310. this.L10 = this.L10.scale(2.094395);
  81311. this.L11 = this.L11.scale(2.094395);
  81312. // Quadratic (Band 2)
  81313. this.L2_2 = this.L2_2.scale(0.785398);
  81314. this.L2_1 = this.L2_1.scale(0.785398);
  81315. this.L20 = this.L20.scale(0.785398);
  81316. this.L21 = this.L21.scale(0.785398);
  81317. this.L22 = this.L22.scale(0.785398);
  81318. };
  81319. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81320. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81321. // L = (1/pi) * E * rho
  81322. //
  81323. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81324. this.scale(1.0 / Math.PI);
  81325. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81326. // (The pixel shader must apply albedo after texture fetches, etc).
  81327. };
  81328. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81329. var result = new SphericalHarmonics();
  81330. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81331. result.L1_1 = polynomial.y.scale(0.977204);
  81332. result.L10 = polynomial.z.scale(0.977204);
  81333. result.L11 = polynomial.x.scale(0.977204);
  81334. result.L2_2 = polynomial.xy.scale(1.16538);
  81335. result.L2_1 = polynomial.yz.scale(1.16538);
  81336. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81337. result.L21 = polynomial.zx.scale(1.16538);
  81338. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81339. result.scale(Math.PI);
  81340. return result;
  81341. };
  81342. return SphericalHarmonics;
  81343. }());
  81344. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81345. })(BABYLON || (BABYLON = {}));
  81346. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81347. var BABYLON;
  81348. (function (BABYLON) {
  81349. var FileFaceOrientation = /** @class */ (function () {
  81350. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81351. this.name = name;
  81352. this.worldAxisForNormal = worldAxisForNormal;
  81353. this.worldAxisForFileX = worldAxisForFileX;
  81354. this.worldAxisForFileY = worldAxisForFileY;
  81355. }
  81356. return FileFaceOrientation;
  81357. }());
  81358. ;
  81359. /**
  81360. * Helper class dealing with the extraction of spherical polynomial dataArray
  81361. * from a cube map.
  81362. */
  81363. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81364. function CubeMapToSphericalPolynomialTools() {
  81365. }
  81366. /**
  81367. * Converts a texture to the according Spherical Polynomial data.
  81368. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81369. *
  81370. * @param texture The texture to extract the information from.
  81371. * @return The Spherical Polynomial data.
  81372. */
  81373. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81374. if (!texture.isCube) {
  81375. // Only supports cube Textures currently.
  81376. return null;
  81377. }
  81378. var size = texture.getSize().width;
  81379. var right = texture.readPixels(0);
  81380. var left = texture.readPixels(1);
  81381. var up;
  81382. var down;
  81383. if (texture.isRenderTarget) {
  81384. up = texture.readPixels(3);
  81385. down = texture.readPixels(2);
  81386. }
  81387. else {
  81388. up = texture.readPixels(2);
  81389. down = texture.readPixels(3);
  81390. }
  81391. var front = texture.readPixels(4);
  81392. var back = texture.readPixels(5);
  81393. var gammaSpace = texture.gammaSpace;
  81394. // Always read as RGBA.
  81395. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81396. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81397. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81398. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81399. }
  81400. var cubeInfo = {
  81401. size: size,
  81402. right: right,
  81403. left: left,
  81404. up: up,
  81405. down: down,
  81406. front: front,
  81407. back: back,
  81408. format: format,
  81409. type: type,
  81410. gammaSpace: gammaSpace,
  81411. };
  81412. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81413. };
  81414. /**
  81415. * Converts a cubemap to the according Spherical Polynomial data.
  81416. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81417. *
  81418. * @param cubeInfo The Cube map to extract the information from.
  81419. * @return The Spherical Polynomial data.
  81420. */
  81421. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81422. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81423. var totalSolidAngle = 0.0;
  81424. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81425. var du = 2.0 / cubeInfo.size;
  81426. var dv = du;
  81427. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81428. var minUV = du * 0.5 - 1.0;
  81429. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81430. var fileFace = this.FileFaces[faceIndex];
  81431. var dataArray = cubeInfo[fileFace.name];
  81432. var v = minUV;
  81433. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81434. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81435. // Because SP is still linear, so summation is fine in that basis.
  81436. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81437. for (var y = 0; y < cubeInfo.size; y++) {
  81438. var u = minUV;
  81439. for (var x = 0; x < cubeInfo.size; x++) {
  81440. // World direction (not normalised)
  81441. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81442. worldDirection.normalize();
  81443. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81444. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81445. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81446. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81447. // Handle Integer types.
  81448. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81449. r /= 255;
  81450. g /= 255;
  81451. b /= 255;
  81452. }
  81453. // Handle Gamma space textures.
  81454. if (cubeInfo.gammaSpace) {
  81455. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81456. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81457. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81458. }
  81459. var color = new BABYLON.Color3(r, g, b);
  81460. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81461. totalSolidAngle += deltaSolidAngle;
  81462. u += du;
  81463. }
  81464. v += dv;
  81465. }
  81466. }
  81467. // Solid angle for entire sphere is 4*pi
  81468. var sphereSolidAngle = 4.0 * Math.PI;
  81469. // Adjust the solid angle to allow for how many faces we processed.
  81470. var facesProcessed = 6.0;
  81471. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81472. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81473. // This is needed because the numerical integration over the cube uses a
  81474. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81475. // and also to compensate for accumulative error due to float precision in the summation.
  81476. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81477. sphericalHarmonics.scale(correctionFactor);
  81478. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81479. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81480. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81481. };
  81482. CubeMapToSphericalPolynomialTools.FileFaces = [
  81483. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81484. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81485. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81486. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81487. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81488. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81489. ];
  81490. return CubeMapToSphericalPolynomialTools;
  81491. }());
  81492. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81493. })(BABYLON || (BABYLON = {}));
  81494. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81495. var BABYLON;
  81496. (function (BABYLON) {
  81497. /**
  81498. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81499. */
  81500. var PanoramaToCubeMapTools = /** @class */ (function () {
  81501. function PanoramaToCubeMapTools() {
  81502. }
  81503. /**
  81504. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81505. *
  81506. * @param float32Array The source data.
  81507. * @param inputWidth The width of the input panorama.
  81508. * @param inputhHeight The height of the input panorama.
  81509. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81510. * @return The cubemap data
  81511. */
  81512. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81513. if (!float32Array) {
  81514. throw "ConvertPanoramaToCubemap: input cannot be null";
  81515. }
  81516. if (float32Array.length != inputWidth * inputHeight * 3) {
  81517. throw "ConvertPanoramaToCubemap: input size is wrong";
  81518. }
  81519. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81520. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81521. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81522. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81523. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81524. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81525. return {
  81526. front: textureFront,
  81527. back: textureBack,
  81528. left: textureLeft,
  81529. right: textureRight,
  81530. up: textureUp,
  81531. down: textureDown,
  81532. size: size,
  81533. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81534. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81535. gammaSpace: false,
  81536. };
  81537. };
  81538. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81539. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81540. var textureArray = new Float32Array(buffer);
  81541. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81542. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81543. var dy = 1 / texSize;
  81544. var fy = 0;
  81545. for (var y = 0; y < texSize; y++) {
  81546. var xv1 = faceData[0];
  81547. var xv2 = faceData[2];
  81548. for (var x = 0; x < texSize; x++) {
  81549. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81550. v.normalize();
  81551. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81552. // 3 channels per pixels
  81553. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81554. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81555. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81556. xv1 = xv1.add(rotDX1);
  81557. xv2 = xv2.add(rotDX2);
  81558. }
  81559. fy += dy;
  81560. }
  81561. return textureArray;
  81562. };
  81563. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81564. var theta = Math.atan2(vDir.z, vDir.x);
  81565. var phi = Math.acos(vDir.y);
  81566. while (theta < -Math.PI)
  81567. theta += 2 * Math.PI;
  81568. while (theta > Math.PI)
  81569. theta -= 2 * Math.PI;
  81570. var dx = theta / Math.PI;
  81571. var dy = phi / Math.PI;
  81572. // recenter.
  81573. dx = dx * 0.5 + 0.5;
  81574. var px = Math.round(dx * inputWidth);
  81575. if (px < 0)
  81576. px = 0;
  81577. else if (px >= inputWidth)
  81578. px = inputWidth - 1;
  81579. var py = Math.round(dy * inputHeight);
  81580. if (py < 0)
  81581. py = 0;
  81582. else if (py >= inputHeight)
  81583. py = inputHeight - 1;
  81584. var inputY = (inputHeight - py - 1);
  81585. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81586. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81587. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81588. return {
  81589. r: r,
  81590. g: g,
  81591. b: b
  81592. };
  81593. };
  81594. PanoramaToCubeMapTools.FACE_FRONT = [
  81595. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81596. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81597. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81598. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81599. ];
  81600. PanoramaToCubeMapTools.FACE_BACK = [
  81601. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81602. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81603. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81604. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81605. ];
  81606. PanoramaToCubeMapTools.FACE_RIGHT = [
  81607. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81608. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81609. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81610. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81611. ];
  81612. PanoramaToCubeMapTools.FACE_LEFT = [
  81613. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81614. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81615. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81616. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81617. ];
  81618. PanoramaToCubeMapTools.FACE_DOWN = [
  81619. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81620. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81621. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81622. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81623. ];
  81624. PanoramaToCubeMapTools.FACE_UP = [
  81625. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81626. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81627. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81628. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81629. ];
  81630. return PanoramaToCubeMapTools;
  81631. }());
  81632. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81633. })(BABYLON || (BABYLON = {}));
  81634. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81635. var BABYLON;
  81636. (function (BABYLON) {
  81637. ;
  81638. /**
  81639. * This groups tools to convert HDR texture to native colors array.
  81640. */
  81641. var HDRTools = /** @class */ (function () {
  81642. function HDRTools() {
  81643. }
  81644. HDRTools.Ldexp = function (mantissa, exponent) {
  81645. if (exponent > 1023) {
  81646. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81647. }
  81648. if (exponent < -1074) {
  81649. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81650. }
  81651. return mantissa * Math.pow(2, exponent);
  81652. };
  81653. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81654. if (exponent > 0) { /*nonzero pixel*/
  81655. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81656. float32array[index + 0] = red * exponent;
  81657. float32array[index + 1] = green * exponent;
  81658. float32array[index + 2] = blue * exponent;
  81659. }
  81660. else {
  81661. float32array[index + 0] = 0;
  81662. float32array[index + 1] = 0;
  81663. float32array[index + 2] = 0;
  81664. }
  81665. };
  81666. HDRTools.readStringLine = function (uint8array, startIndex) {
  81667. var line = "";
  81668. var character = "";
  81669. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81670. character = String.fromCharCode(uint8array[i]);
  81671. if (character == "\n") {
  81672. break;
  81673. }
  81674. line += character;
  81675. }
  81676. return line;
  81677. };
  81678. /**
  81679. * Reads header information from an RGBE texture stored in a native array.
  81680. * More information on this format are available here:
  81681. * https://en.wikipedia.org/wiki/RGBE_image_format
  81682. *
  81683. * @param uint8array The binary file stored in native array.
  81684. * @return The header information.
  81685. */
  81686. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81687. var height = 0;
  81688. var width = 0;
  81689. var line = this.readStringLine(uint8array, 0);
  81690. if (line[0] != '#' || line[1] != '?') {
  81691. throw "Bad HDR Format.";
  81692. }
  81693. var endOfHeader = false;
  81694. var findFormat = false;
  81695. var lineIndex = 0;
  81696. do {
  81697. lineIndex += (line.length + 1);
  81698. line = this.readStringLine(uint8array, lineIndex);
  81699. if (line == "FORMAT=32-bit_rle_rgbe") {
  81700. findFormat = true;
  81701. }
  81702. else if (line.length == 0) {
  81703. endOfHeader = true;
  81704. }
  81705. } while (!endOfHeader);
  81706. if (!findFormat) {
  81707. throw "HDR Bad header format, unsupported FORMAT";
  81708. }
  81709. lineIndex += (line.length + 1);
  81710. line = this.readStringLine(uint8array, lineIndex);
  81711. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  81712. var match = sizeRegexp.exec(line);
  81713. // TODO. Support +Y and -X if needed.
  81714. if (!match || match.length < 3) {
  81715. throw "HDR Bad header format, no size";
  81716. }
  81717. width = parseInt(match[2]);
  81718. height = parseInt(match[1]);
  81719. if (width < 8 || width > 0x7fff) {
  81720. throw "HDR Bad header format, unsupported size";
  81721. }
  81722. lineIndex += (line.length + 1);
  81723. return {
  81724. height: height,
  81725. width: width,
  81726. dataPosition: lineIndex
  81727. };
  81728. };
  81729. /**
  81730. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  81731. * This RGBE texture needs to store the information as a panorama.
  81732. *
  81733. * More information on this format are available here:
  81734. * https://en.wikipedia.org/wiki/RGBE_image_format
  81735. *
  81736. * @param buffer The binary file stored in an array buffer.
  81737. * @param size The expected size of the extracted cubemap.
  81738. * @return The Cube Map information.
  81739. */
  81740. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  81741. var uint8array = new Uint8Array(buffer);
  81742. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  81743. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81744. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  81745. return cubeMapData;
  81746. };
  81747. /**
  81748. * Returns the pixels data extracted from an RGBE texture.
  81749. * This pixels will be stored left to right up to down in the R G B order in one array.
  81750. *
  81751. * More information on this format are available here:
  81752. * https://en.wikipedia.org/wiki/RGBE_image_format
  81753. *
  81754. * @param uint8array The binary file stored in an array buffer.
  81755. * @param hdrInfo The header information of the file.
  81756. * @return The pixels data in RGB right to left up to down order.
  81757. */
  81758. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  81759. // Keep for multi format supports.
  81760. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  81761. };
  81762. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  81763. var num_scanlines = hdrInfo.height;
  81764. var scanline_width = hdrInfo.width;
  81765. var a, b, c, d, count;
  81766. var dataIndex = hdrInfo.dataPosition;
  81767. var index = 0, endIndex = 0, i = 0;
  81768. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  81769. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  81770. // 3 channels of 4 bytes per pixel in float.
  81771. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  81772. var resultArray = new Float32Array(resultBuffer);
  81773. // read in each successive scanline
  81774. while (num_scanlines > 0) {
  81775. a = uint8array[dataIndex++];
  81776. b = uint8array[dataIndex++];
  81777. c = uint8array[dataIndex++];
  81778. d = uint8array[dataIndex++];
  81779. if (a != 2 || b != 2 || (c & 0x80)) {
  81780. // this file is not run length encoded
  81781. throw "HDR Bad header format, not RLE";
  81782. }
  81783. if (((c << 8) | d) != scanline_width) {
  81784. throw "HDR Bad header format, wrong scan line width";
  81785. }
  81786. index = 0;
  81787. // read each of the four channels for the scanline into the buffer
  81788. for (i = 0; i < 4; i++) {
  81789. endIndex = (i + 1) * scanline_width;
  81790. while (index < endIndex) {
  81791. a = uint8array[dataIndex++];
  81792. b = uint8array[dataIndex++];
  81793. if (a > 128) {
  81794. // a run of the same value
  81795. count = a - 128;
  81796. if ((count == 0) || (count > endIndex - index)) {
  81797. throw "HDR Bad Format, bad scanline data (run)";
  81798. }
  81799. while (count-- > 0) {
  81800. scanLineArray[index++] = b;
  81801. }
  81802. }
  81803. else {
  81804. // a non-run
  81805. count = a;
  81806. if ((count == 0) || (count > endIndex - index)) {
  81807. throw "HDR Bad Format, bad scanline data (non-run)";
  81808. }
  81809. scanLineArray[index++] = b;
  81810. if (--count > 0) {
  81811. for (var j = 0; j < count; j++) {
  81812. scanLineArray[index++] = uint8array[dataIndex++];
  81813. }
  81814. }
  81815. }
  81816. }
  81817. }
  81818. // now convert data from buffer into floats
  81819. for (i = 0; i < scanline_width; i++) {
  81820. a = scanLineArray[i];
  81821. b = scanLineArray[i + scanline_width];
  81822. c = scanLineArray[i + 2 * scanline_width];
  81823. d = scanLineArray[i + 3 * scanline_width];
  81824. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  81825. }
  81826. num_scanlines--;
  81827. }
  81828. return resultArray;
  81829. };
  81830. return HDRTools;
  81831. }());
  81832. BABYLON.HDRTools = HDRTools;
  81833. })(BABYLON || (BABYLON = {}));
  81834. //# sourceMappingURL=babylon.hdr.js.map
  81835. var BABYLON;
  81836. (function (BABYLON) {
  81837. /**
  81838. * Sets of helpers addressing the serialization and deserialization of environment texture
  81839. * stored in a BabylonJS env file.
  81840. * Those files are usually stored as .env files.
  81841. */
  81842. var EnvironmentTextureTools = /** @class */ (function () {
  81843. function EnvironmentTextureTools() {
  81844. }
  81845. /**
  81846. * Gets the environment info from an env file.
  81847. * @param data The array buffer containing the .env bytes.
  81848. * @returns the environment file info (the json header) if successfully parsed.
  81849. */
  81850. EnvironmentTextureTools.GetEnvInfo = function (data) {
  81851. var dataView = new DataView(data);
  81852. var pos = 0;
  81853. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81854. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  81855. BABYLON.Tools.Error('Not a babylon environment map');
  81856. return null;
  81857. }
  81858. }
  81859. // Read json manifest - collect characters up to null terminator
  81860. var manifestString = '';
  81861. var charCode = 0x00;
  81862. while ((charCode = dataView.getUint8(pos++))) {
  81863. manifestString += String.fromCharCode(charCode);
  81864. }
  81865. var manifest = JSON.parse(manifestString);
  81866. if (manifest.specular) {
  81867. // Extend the header with the position of the payload.
  81868. manifest.specular.specularDataPosition = pos;
  81869. }
  81870. return manifest;
  81871. };
  81872. /**
  81873. * Creates an environment texture from a loaded cube texture.
  81874. * @param texture defines the cube texture to convert in env file
  81875. * @return a promise containing the environment data if succesfull.
  81876. */
  81877. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  81878. var _this = this;
  81879. var internalTexture = texture.getInternalTexture();
  81880. if (!internalTexture) {
  81881. return Promise.reject("The cube texture is invalid.");
  81882. }
  81883. if (!texture._prefiltered) {
  81884. return Promise.reject("The cube texture is invalid (not prefiltered).");
  81885. }
  81886. var engine = internalTexture.getEngine();
  81887. if (engine && engine.premultipliedAlpha) {
  81888. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  81889. }
  81890. var canvas = engine.getRenderingCanvas();
  81891. if (!canvas) {
  81892. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  81893. }
  81894. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81895. if (!engine.getCaps().textureFloatRender) {
  81896. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  81897. if (!engine.getCaps().textureHalfFloatRender) {
  81898. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  81899. }
  81900. }
  81901. var cubeWidth = internalTexture.width;
  81902. var hostingScene = new BABYLON.Scene(engine);
  81903. var specularTextures = {};
  81904. var promises = [];
  81905. // Read and collect all mipmaps data from the cube.
  81906. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  81907. mipmapsCount = Math.round(mipmapsCount);
  81908. var _loop_1 = function (i) {
  81909. var faceWidth = Math.pow(2, mipmapsCount - i);
  81910. var _loop_2 = function (face) {
  81911. var data = texture.readPixels(face, i);
  81912. // Creates a temp texture with the face data.
  81913. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  81914. // And rgbdEncode them.
  81915. var promise = new Promise(function (resolve, reject) {
  81916. 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);
  81917. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  81918. rgbdPostProcess.onApply = function (effect) {
  81919. effect._bindTexture("textureSampler", tempTexture);
  81920. };
  81921. // As the process needs to happen on the main canvas, keep track of the current size
  81922. var currentW = engine.getRenderWidth();
  81923. var currentH = engine.getRenderHeight();
  81924. // Set the desired size for the texture
  81925. engine.setSize(faceWidth, faceWidth);
  81926. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  81927. // Reading datas from WebGL
  81928. canvas.toBlob(function (blob) {
  81929. var fileReader = new FileReader();
  81930. fileReader.onload = function (event) {
  81931. var arrayBuffer = event.target.result;
  81932. specularTextures[i * 6 + face] = arrayBuffer;
  81933. resolve();
  81934. };
  81935. fileReader.readAsArrayBuffer(blob);
  81936. });
  81937. // Reapply the previous canvas size
  81938. engine.setSize(currentW, currentH);
  81939. });
  81940. });
  81941. promises.push(promise);
  81942. };
  81943. // All faces of the cube.
  81944. for (var face = 0; face < 6; face++) {
  81945. _loop_2(face);
  81946. }
  81947. };
  81948. for (var i = 0; i <= mipmapsCount; i++) {
  81949. _loop_1(i);
  81950. }
  81951. // Once all the textures haves been collected as RGBD stored in PNGs
  81952. return Promise.all(promises).then(function () {
  81953. // We can delete the hosting scene keeping track of all the creation objects
  81954. hostingScene.dispose();
  81955. // Creates the json header for the env texture
  81956. var info = {
  81957. version: 1,
  81958. width: cubeWidth,
  81959. irradiance: _this._CreateEnvTextureIrradiance(texture),
  81960. specular: {
  81961. mipmaps: []
  81962. }
  81963. };
  81964. // Sets the specular image data information
  81965. var position = 0;
  81966. for (var i = 0; i <= mipmapsCount; i++) {
  81967. for (var face = 0; face < 6; face++) {
  81968. var byteLength = specularTextures[i * 6 + face].byteLength;
  81969. info.specular.mipmaps.push({
  81970. length: byteLength,
  81971. position: position
  81972. });
  81973. position += byteLength;
  81974. }
  81975. }
  81976. // Encode the JSON as an array buffer
  81977. var infoString = JSON.stringify(info);
  81978. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  81979. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  81980. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  81981. infoView[i] = infoString.charCodeAt(i);
  81982. }
  81983. // Ends up with a null terminator for easier parsing
  81984. infoView[infoString.length] = 0x00;
  81985. // Computes the final required size and creates the storage
  81986. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  81987. var finalBuffer = new ArrayBuffer(totalSize);
  81988. var finalBufferView = new Uint8Array(finalBuffer);
  81989. var dataView = new DataView(finalBuffer);
  81990. // Copy the magic bytes identifying the file in
  81991. var pos = 0;
  81992. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  81993. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  81994. }
  81995. // Add the json info
  81996. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  81997. pos += infoBuffer.byteLength;
  81998. // Finally inserts the texture data
  81999. for (var i = 0; i <= mipmapsCount; i++) {
  82000. for (var face = 0; face < 6; face++) {
  82001. var dataBuffer = specularTextures[i * 6 + face];
  82002. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82003. pos += dataBuffer.byteLength;
  82004. }
  82005. }
  82006. // Voila
  82007. return finalBuffer;
  82008. });
  82009. };
  82010. /**
  82011. * Creates a JSON representation of the spherical data.
  82012. * @param texture defines the texture containing the polynomials
  82013. * @return the JSON representation of the spherical info
  82014. */
  82015. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82016. var polynmials = texture.sphericalPolynomial;
  82017. if (polynmials == null) {
  82018. return null;
  82019. }
  82020. return {
  82021. polynomials: true,
  82022. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82023. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82024. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82025. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82026. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82027. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82028. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82029. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82030. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82031. };
  82032. };
  82033. /**
  82034. * Uploads the texture info contained in the env file to te GPU.
  82035. * @param texture defines the internal texture to upload to
  82036. * @param arrayBuffer defines the buffer cotaining the data to load
  82037. * @param info defines the texture info retrieved through the GetEnvInfo method
  82038. * @returns a promise
  82039. */
  82040. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82041. if (info.version !== 1) {
  82042. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82043. }
  82044. var specularInfo = info.specular;
  82045. if (!specularInfo) {
  82046. // Nothing else parsed so far
  82047. return Promise.resolve();
  82048. }
  82049. // Double checks the enclosed info
  82050. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82051. mipmapsCount = Math.round(mipmapsCount) + 1;
  82052. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82053. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82054. }
  82055. // Gets everything ready.
  82056. var engine = texture.getEngine();
  82057. var expandTexture = false;
  82058. var generateNonLODTextures = false;
  82059. var rgbdPostProcess = null;
  82060. var cubeRtt = null;
  82061. var lodTextures = null;
  82062. var caps = engine.getCaps();
  82063. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82064. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82065. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82066. // Add extra process if texture lod is not supported
  82067. if (!caps.textureLOD) {
  82068. expandTexture = false;
  82069. generateNonLODTextures = true;
  82070. lodTextures = {};
  82071. }
  82072. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82073. else if (engine.webGLVersion < 2) {
  82074. expandTexture = false;
  82075. }
  82076. // If half float available we can uncompress the texture
  82077. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82078. expandTexture = true;
  82079. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82080. }
  82081. // If full float available we can uncompress the texture
  82082. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82083. expandTexture = true;
  82084. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82085. }
  82086. // Expand the texture if possible
  82087. if (expandTexture) {
  82088. // Simply run through the decode PP
  82089. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82090. texture._isRGBD = false;
  82091. texture.invertY = false;
  82092. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82093. generateDepthBuffer: false,
  82094. generateMipMaps: true,
  82095. generateStencilBuffer: false,
  82096. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82097. type: texture.type,
  82098. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82099. });
  82100. }
  82101. else {
  82102. texture._isRGBD = true;
  82103. texture.invertY = true;
  82104. // In case of missing support, applies the same patch than DDS files.
  82105. if (generateNonLODTextures) {
  82106. var mipSlices = 3;
  82107. var scale = texture._lodGenerationScale;
  82108. var offset = texture._lodGenerationOffset;
  82109. for (var i = 0; i < mipSlices; i++) {
  82110. //compute LOD from even spacing in smoothness (matching shader calculation)
  82111. var smoothness = i / (mipSlices - 1);
  82112. var roughness = 1 - smoothness;
  82113. var minLODIndex = offset; // roughness = 0
  82114. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82115. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82116. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82117. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82118. glTextureFromLod.isCube = true;
  82119. glTextureFromLod.invertY = true;
  82120. glTextureFromLod.generateMipMaps = false;
  82121. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82122. // Wrap in a base texture for easy binding.
  82123. var lodTexture = new BABYLON.BaseTexture(null);
  82124. lodTexture.isCube = true;
  82125. lodTexture._texture = glTextureFromLod;
  82126. lodTextures[mipmapIndex] = lodTexture;
  82127. switch (i) {
  82128. case 0:
  82129. texture._lodTextureLow = lodTexture;
  82130. break;
  82131. case 1:
  82132. texture._lodTextureMid = lodTexture;
  82133. break;
  82134. case 2:
  82135. texture._lodTextureHigh = lodTexture;
  82136. break;
  82137. }
  82138. }
  82139. }
  82140. }
  82141. var promises = [];
  82142. var _loop_3 = function (i) {
  82143. var _loop_4 = function (face) {
  82144. // Retrieves the face data
  82145. var imageData = specularInfo.mipmaps[i * 6 + face];
  82146. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82147. // Constructs an image element from bytes
  82148. var blob = new Blob([bytes], { type: 'image/png' });
  82149. var url = URL.createObjectURL(blob);
  82150. var image = new Image();
  82151. image.src = url;
  82152. // Enqueue promise to upload to the texture.
  82153. var promise = new Promise(function (resolve, reject) {
  82154. ;
  82155. image.onload = function () {
  82156. if (expandTexture) {
  82157. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82158. reject(message);
  82159. }, image);
  82160. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82161. // Uncompress the data to a RTT
  82162. rgbdPostProcess.onApply = function (effect) {
  82163. effect._bindTexture("textureSampler", tempTexture_1);
  82164. effect.setFloat2("scale", 1, 1);
  82165. };
  82166. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82167. // Cleanup
  82168. engine.restoreDefaultFramebuffer();
  82169. tempTexture_1.dispose();
  82170. window.URL.revokeObjectURL(url);
  82171. resolve();
  82172. });
  82173. }
  82174. else {
  82175. engine._uploadImageToTexture(texture, face, i, image);
  82176. // Upload the face to the none lod texture support
  82177. if (generateNonLODTextures) {
  82178. var lodTexture = lodTextures[i];
  82179. if (lodTexture) {
  82180. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82181. }
  82182. }
  82183. resolve();
  82184. }
  82185. };
  82186. image.onerror = function (error) {
  82187. reject(error);
  82188. };
  82189. });
  82190. promises.push(promise);
  82191. };
  82192. // All faces
  82193. for (var face = 0; face < 6; face++) {
  82194. _loop_4(face);
  82195. }
  82196. };
  82197. // All mipmaps
  82198. for (var i = 0; i < mipmapsCount; i++) {
  82199. _loop_3(i);
  82200. }
  82201. // Once all done, finishes the cleanup and return
  82202. return Promise.all(promises).then(function () {
  82203. // Relase temp RTT.
  82204. if (cubeRtt) {
  82205. engine._releaseFramebufferObjects(cubeRtt);
  82206. cubeRtt._swapAndDie(texture);
  82207. }
  82208. // Relase temp Post Process.
  82209. if (rgbdPostProcess) {
  82210. rgbdPostProcess.dispose();
  82211. }
  82212. // Flag internal texture as ready in case they are in use.
  82213. if (generateNonLODTextures) {
  82214. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82215. texture._lodTextureHigh._texture.isReady = true;
  82216. }
  82217. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82218. texture._lodTextureMid._texture.isReady = true;
  82219. }
  82220. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82221. texture._lodTextureLow._texture.isReady = true;
  82222. }
  82223. }
  82224. });
  82225. };
  82226. /**
  82227. * Uploads spherical polynomials information to the texture.
  82228. * @param texture defines the texture we are trying to upload the information to
  82229. * @param arrayBuffer defines the array buffer holding the data
  82230. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82231. */
  82232. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82233. if (info.version !== 1) {
  82234. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82235. }
  82236. var irradianceInfo = info.irradiance;
  82237. if (!irradianceInfo) {
  82238. return;
  82239. }
  82240. //harmonics now represent radiance
  82241. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82242. if (irradianceInfo.polynomials) {
  82243. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82244. }
  82245. else {
  82246. // convert From SH to SP.
  82247. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82248. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82249. }
  82250. };
  82251. /**
  82252. * Upload spherical polynomial coefficients to the texture
  82253. * @param polynmials Spherical polynmial coefficients (9)
  82254. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82255. */
  82256. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82257. outPolynomialCoefficents.x.x = polynmials.x[0];
  82258. outPolynomialCoefficents.x.y = polynmials.x[1];
  82259. outPolynomialCoefficents.x.z = polynmials.x[2];
  82260. outPolynomialCoefficents.y.x = polynmials.y[0];
  82261. outPolynomialCoefficents.y.y = polynmials.y[1];
  82262. outPolynomialCoefficents.y.z = polynmials.y[2];
  82263. outPolynomialCoefficents.z.x = polynmials.z[0];
  82264. outPolynomialCoefficents.z.y = polynmials.z[1];
  82265. outPolynomialCoefficents.z.z = polynmials.z[2];
  82266. //xx
  82267. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82268. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82269. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82270. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82271. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82272. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82273. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82274. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82275. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82276. //yz
  82277. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82278. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82279. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82280. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82281. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82282. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82283. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82284. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82285. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82286. };
  82287. /**
  82288. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82289. * L = (1/pi) * E * rho
  82290. *
  82291. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82292. * @param harmonics Spherical harmonic coefficients (9)
  82293. */
  82294. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82295. var scaleFactor = 1 / Math.PI;
  82296. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82297. // (The pixel shader must apply albedo after texture fetches, etc).
  82298. harmonics.l00[0] *= scaleFactor;
  82299. harmonics.l00[1] *= scaleFactor;
  82300. harmonics.l00[2] *= scaleFactor;
  82301. harmonics.l1_1[0] *= scaleFactor;
  82302. harmonics.l1_1[1] *= scaleFactor;
  82303. harmonics.l1_1[2] *= scaleFactor;
  82304. harmonics.l10[0] *= scaleFactor;
  82305. harmonics.l10[1] *= scaleFactor;
  82306. harmonics.l10[2] *= scaleFactor;
  82307. harmonics.l11[0] *= scaleFactor;
  82308. harmonics.l11[1] *= scaleFactor;
  82309. harmonics.l11[2] *= scaleFactor;
  82310. harmonics.l2_2[0] *= scaleFactor;
  82311. harmonics.l2_2[1] *= scaleFactor;
  82312. harmonics.l2_2[2] *= scaleFactor;
  82313. harmonics.l2_1[0] *= scaleFactor;
  82314. harmonics.l2_1[1] *= scaleFactor;
  82315. harmonics.l2_1[2] *= scaleFactor;
  82316. harmonics.l20[0] *= scaleFactor;
  82317. harmonics.l20[1] *= scaleFactor;
  82318. harmonics.l20[2] *= scaleFactor;
  82319. harmonics.l21[0] *= scaleFactor;
  82320. harmonics.l21[1] *= scaleFactor;
  82321. harmonics.l21[2] *= scaleFactor;
  82322. harmonics.l22[0] *= scaleFactor;
  82323. harmonics.l22[1] *= scaleFactor;
  82324. harmonics.l22[2] *= scaleFactor;
  82325. };
  82326. /**
  82327. * Convert spherical harmonics to spherical polynomial coefficients
  82328. * @param harmonics Spherical harmonic coefficients (9)
  82329. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82330. */
  82331. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82332. var rPi = 1 / Math.PI;
  82333. //x
  82334. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82335. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82336. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82337. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82338. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82339. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82340. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82341. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82342. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82343. //xx
  82344. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82345. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82346. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82347. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82348. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82349. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82350. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82351. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82352. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82353. //yz
  82354. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82355. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82356. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82357. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82358. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82359. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82360. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82361. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82362. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82363. };
  82364. /**
  82365. * Magic number identifying the env file.
  82366. */
  82367. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82368. return EnvironmentTextureTools;
  82369. }());
  82370. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82371. })(BABYLON || (BABYLON = {}));
  82372. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82373. var BABYLON;
  82374. (function (BABYLON) {
  82375. /**
  82376. * This represents a texture coming from an HDR input.
  82377. *
  82378. * The only supported format is currently panorama picture stored in RGBE format.
  82379. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82380. */
  82381. var HDRCubeTexture = /** @class */ (function (_super) {
  82382. __extends(HDRCubeTexture, _super);
  82383. /**
  82384. * Instantiates an HDRTexture from the following parameters.
  82385. *
  82386. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82387. * @param scene The scene the texture will be used in
  82388. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82389. * @param noMipmap Forces to not generate the mipmap if true
  82390. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82391. * @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)
  82392. * @param reserved Reserved flag for internal use.
  82393. */
  82394. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82395. if (noMipmap === void 0) { noMipmap = false; }
  82396. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82397. if (gammaSpace === void 0) { gammaSpace = false; }
  82398. if (reserved === void 0) { reserved = false; }
  82399. if (onLoad === void 0) { onLoad = null; }
  82400. if (onError === void 0) { onError = null; }
  82401. var _this = _super.call(this, scene) || this;
  82402. _this._generateHarmonics = true;
  82403. _this._onLoad = null;
  82404. _this._onError = null;
  82405. /**
  82406. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82407. */
  82408. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82409. _this._isBlocking = true;
  82410. _this._rotationY = 0;
  82411. /**
  82412. * Gets or sets the center of the bounding box associated with the cube texture
  82413. * It must define where the camera used to render the texture was set
  82414. */
  82415. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82416. if (!url) {
  82417. return _this;
  82418. }
  82419. _this.name = url;
  82420. _this.url = url;
  82421. _this.hasAlpha = false;
  82422. _this.isCube = true;
  82423. _this._textureMatrix = BABYLON.Matrix.Identity();
  82424. _this._onLoad = onLoad;
  82425. _this._onError = onError;
  82426. _this.gammaSpace = gammaSpace;
  82427. _this._noMipmap = noMipmap;
  82428. _this._size = size;
  82429. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82430. if (!_this._texture) {
  82431. if (!scene.useDelayedTextureLoading) {
  82432. _this.loadTexture();
  82433. }
  82434. else {
  82435. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82436. }
  82437. }
  82438. return _this;
  82439. }
  82440. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82441. /**
  82442. * Gets wether or not the texture is blocking during loading.
  82443. */
  82444. get: function () {
  82445. return this._isBlocking;
  82446. },
  82447. /**
  82448. * Sets wether or not the texture is blocking during loading.
  82449. */
  82450. set: function (value) {
  82451. this._isBlocking = value;
  82452. },
  82453. enumerable: true,
  82454. configurable: true
  82455. });
  82456. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82457. /**
  82458. * Gets texture matrix rotation angle around Y axis radians.
  82459. */
  82460. get: function () {
  82461. return this._rotationY;
  82462. },
  82463. /**
  82464. * Sets texture matrix rotation angle around Y axis in radians.
  82465. */
  82466. set: function (value) {
  82467. this._rotationY = value;
  82468. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82469. },
  82470. enumerable: true,
  82471. configurable: true
  82472. });
  82473. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82474. get: function () {
  82475. return this._boundingBoxSize;
  82476. },
  82477. /**
  82478. * Gets or sets the size of the bounding box associated with the cube texture
  82479. * When defined, the cubemap will switch to local mode
  82480. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82481. * @example https://www.babylonjs-playground.com/#RNASML
  82482. */
  82483. set: function (value) {
  82484. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82485. return;
  82486. }
  82487. this._boundingBoxSize = value;
  82488. var scene = this.getScene();
  82489. if (scene) {
  82490. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82491. }
  82492. },
  82493. enumerable: true,
  82494. configurable: true
  82495. });
  82496. /**
  82497. * Occurs when the file is raw .hdr file.
  82498. */
  82499. HDRCubeTexture.prototype.loadTexture = function () {
  82500. var _this = this;
  82501. var callback = function (buffer) {
  82502. _this.lodGenerationOffset = 0.0;
  82503. _this.lodGenerationScale = 0.8;
  82504. var scene = _this.getScene();
  82505. if (!scene) {
  82506. return null;
  82507. }
  82508. // Extract the raw linear data.
  82509. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82510. // Generate harmonics if needed.
  82511. if (_this._generateHarmonics) {
  82512. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82513. _this.sphericalPolynomial = sphericalPolynomial;
  82514. }
  82515. var results = [];
  82516. var byteArray = null;
  82517. // Push each faces.
  82518. for (var j = 0; j < 6; j++) {
  82519. // Create uintarray fallback.
  82520. if (!scene.getEngine().getCaps().textureFloat) {
  82521. // 3 channels of 1 bytes per pixel in bytes.
  82522. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82523. byteArray = new Uint8Array(byteBuffer);
  82524. }
  82525. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82526. // If special cases.
  82527. if (_this.gammaSpace || byteArray) {
  82528. for (var i = 0; i < _this._size * _this._size; i++) {
  82529. // Put in gamma space if requested.
  82530. if (_this.gammaSpace) {
  82531. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82532. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82533. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82534. }
  82535. // Convert to int texture for fallback.
  82536. if (byteArray) {
  82537. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82538. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82539. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82540. // May use luminance instead if the result is not accurate.
  82541. var max = Math.max(Math.max(r, g), b);
  82542. if (max > 255) {
  82543. var scale = 255 / max;
  82544. r *= scale;
  82545. g *= scale;
  82546. b *= scale;
  82547. }
  82548. byteArray[(i * 3) + 0] = r;
  82549. byteArray[(i * 3) + 1] = g;
  82550. byteArray[(i * 3) + 2] = b;
  82551. }
  82552. }
  82553. }
  82554. if (byteArray) {
  82555. results.push(byteArray);
  82556. }
  82557. else {
  82558. results.push(dataFace);
  82559. }
  82560. }
  82561. return results;
  82562. };
  82563. var scene = this.getScene();
  82564. if (scene) {
  82565. 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);
  82566. }
  82567. };
  82568. HDRCubeTexture.prototype.clone = function () {
  82569. var scene = this.getScene();
  82570. if (!scene) {
  82571. return this;
  82572. }
  82573. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82574. // Base texture
  82575. newTexture.level = this.level;
  82576. newTexture.wrapU = this.wrapU;
  82577. newTexture.wrapV = this.wrapV;
  82578. newTexture.coordinatesIndex = this.coordinatesIndex;
  82579. newTexture.coordinatesMode = this.coordinatesMode;
  82580. return newTexture;
  82581. };
  82582. // Methods
  82583. HDRCubeTexture.prototype.delayLoad = function () {
  82584. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82585. return;
  82586. }
  82587. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82588. this._texture = this._getFromCache(this.url, this._noMipmap);
  82589. if (!this._texture) {
  82590. this.loadTexture();
  82591. }
  82592. };
  82593. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82594. return this._textureMatrix;
  82595. };
  82596. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82597. this._textureMatrix = value;
  82598. };
  82599. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82600. var texture = null;
  82601. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82602. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82603. texture.name = parsedTexture.name;
  82604. texture.hasAlpha = parsedTexture.hasAlpha;
  82605. texture.level = parsedTexture.level;
  82606. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82607. texture.isBlocking = parsedTexture.isBlocking;
  82608. }
  82609. if (texture) {
  82610. if (parsedTexture.boundingBoxPosition) {
  82611. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82612. }
  82613. if (parsedTexture.boundingBoxSize) {
  82614. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82615. }
  82616. if (parsedTexture.rotationY) {
  82617. texture.rotationY = parsedTexture.rotationY;
  82618. }
  82619. }
  82620. return texture;
  82621. };
  82622. HDRCubeTexture.prototype.serialize = function () {
  82623. if (!this.name) {
  82624. return null;
  82625. }
  82626. var serializationObject = {};
  82627. serializationObject.name = this.name;
  82628. serializationObject.hasAlpha = this.hasAlpha;
  82629. serializationObject.isCube = true;
  82630. serializationObject.level = this.level;
  82631. serializationObject.size = this._size;
  82632. serializationObject.coordinatesMode = this.coordinatesMode;
  82633. serializationObject.useInGammaSpace = this.gammaSpace;
  82634. serializationObject.generateHarmonics = this._generateHarmonics;
  82635. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82636. serializationObject.noMipmap = this._noMipmap;
  82637. serializationObject.isBlocking = this._isBlocking;
  82638. serializationObject.rotationY = this._rotationY;
  82639. return serializationObject;
  82640. };
  82641. HDRCubeTexture._facesMapping = [
  82642. "right",
  82643. "left",
  82644. "up",
  82645. "down",
  82646. "front",
  82647. "back"
  82648. ];
  82649. return HDRCubeTexture;
  82650. }(BABYLON.BaseTexture));
  82651. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82652. })(BABYLON || (BABYLON = {}));
  82653. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82654. var BABYLON;
  82655. (function (BABYLON) {
  82656. var IndexedVector2 = /** @class */ (function (_super) {
  82657. __extends(IndexedVector2, _super);
  82658. function IndexedVector2(original, index) {
  82659. var _this = _super.call(this, original.x, original.y) || this;
  82660. _this.index = index;
  82661. return _this;
  82662. }
  82663. return IndexedVector2;
  82664. }(BABYLON.Vector2));
  82665. var PolygonPoints = /** @class */ (function () {
  82666. function PolygonPoints() {
  82667. this.elements = new Array();
  82668. }
  82669. PolygonPoints.prototype.add = function (originalPoints) {
  82670. var _this = this;
  82671. var result = new Array();
  82672. originalPoints.forEach(function (point) {
  82673. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82674. var newPoint = new IndexedVector2(point, _this.elements.length);
  82675. result.push(newPoint);
  82676. _this.elements.push(newPoint);
  82677. }
  82678. });
  82679. return result;
  82680. };
  82681. PolygonPoints.prototype.computeBounds = function () {
  82682. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82683. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82684. this.elements.forEach(function (point) {
  82685. // x
  82686. if (point.x < lmin.x) {
  82687. lmin.x = point.x;
  82688. }
  82689. else if (point.x > lmax.x) {
  82690. lmax.x = point.x;
  82691. }
  82692. // y
  82693. if (point.y < lmin.y) {
  82694. lmin.y = point.y;
  82695. }
  82696. else if (point.y > lmax.y) {
  82697. lmax.y = point.y;
  82698. }
  82699. });
  82700. return {
  82701. min: lmin,
  82702. max: lmax,
  82703. width: lmax.x - lmin.x,
  82704. height: lmax.y - lmin.y
  82705. };
  82706. };
  82707. return PolygonPoints;
  82708. }());
  82709. var Polygon = /** @class */ (function () {
  82710. function Polygon() {
  82711. }
  82712. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  82713. return [
  82714. new BABYLON.Vector2(xmin, ymin),
  82715. new BABYLON.Vector2(xmax, ymin),
  82716. new BABYLON.Vector2(xmax, ymax),
  82717. new BABYLON.Vector2(xmin, ymax)
  82718. ];
  82719. };
  82720. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  82721. if (cx === void 0) { cx = 0; }
  82722. if (cy === void 0) { cy = 0; }
  82723. if (numberOfSides === void 0) { numberOfSides = 32; }
  82724. var result = new Array();
  82725. var angle = 0;
  82726. var increment = (Math.PI * 2) / numberOfSides;
  82727. for (var i = 0; i < numberOfSides; i++) {
  82728. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  82729. angle -= increment;
  82730. }
  82731. return result;
  82732. };
  82733. Polygon.Parse = function (input) {
  82734. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  82735. var i, result = [];
  82736. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  82737. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  82738. }
  82739. return result;
  82740. };
  82741. Polygon.StartingAt = function (x, y) {
  82742. return BABYLON.Path2.StartingAt(x, y);
  82743. };
  82744. return Polygon;
  82745. }());
  82746. BABYLON.Polygon = Polygon;
  82747. var PolygonMeshBuilder = /** @class */ (function () {
  82748. function PolygonMeshBuilder(name, contours, scene) {
  82749. this._points = new PolygonPoints();
  82750. this._outlinepoints = new PolygonPoints();
  82751. this._holes = new Array();
  82752. this._epoints = new Array();
  82753. this._eholes = new Array();
  82754. this._name = name;
  82755. this._scene = scene;
  82756. var points;
  82757. if (contours instanceof BABYLON.Path2) {
  82758. points = contours.getPoints();
  82759. }
  82760. else {
  82761. points = contours;
  82762. }
  82763. this._addToepoint(points);
  82764. this._points.add(points);
  82765. this._outlinepoints.add(points);
  82766. if (typeof earcut === 'undefined') {
  82767. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  82768. }
  82769. }
  82770. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  82771. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  82772. var p = points_1[_i];
  82773. this._epoints.push(p.x, p.y);
  82774. }
  82775. };
  82776. PolygonMeshBuilder.prototype.addHole = function (hole) {
  82777. this._points.add(hole);
  82778. var holepoints = new PolygonPoints();
  82779. holepoints.add(hole);
  82780. this._holes.push(holepoints);
  82781. this._eholes.push(this._epoints.length / 2);
  82782. this._addToepoint(hole);
  82783. return this;
  82784. };
  82785. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  82786. var _this = this;
  82787. if (updatable === void 0) { updatable = false; }
  82788. if (depth === void 0) { depth = 0; }
  82789. var result = new BABYLON.Mesh(this._name, this._scene);
  82790. var normals = new Array();
  82791. var positions = new Array();
  82792. var uvs = new Array();
  82793. var bounds = this._points.computeBounds();
  82794. this._points.elements.forEach(function (p) {
  82795. normals.push(0, 1.0, 0);
  82796. positions.push(p.x, 0, p.y);
  82797. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  82798. });
  82799. var indices = new Array();
  82800. var res = earcut(this._epoints, this._eholes, 2);
  82801. for (var i = 0; i < res.length; i++) {
  82802. indices.push(res[i]);
  82803. }
  82804. if (depth > 0) {
  82805. var positionscount = (positions.length / 3); //get the current pointcount
  82806. this._points.elements.forEach(function (p) {
  82807. normals.push(0, -1.0, 0);
  82808. positions.push(p.x, -depth, p.y);
  82809. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  82810. });
  82811. var totalCount = indices.length;
  82812. for (var i = 0; i < totalCount; i += 3) {
  82813. var i0 = indices[i + 0];
  82814. var i1 = indices[i + 1];
  82815. var i2 = indices[i + 2];
  82816. indices.push(i2 + positionscount);
  82817. indices.push(i1 + positionscount);
  82818. indices.push(i0 + positionscount);
  82819. }
  82820. //Add the sides
  82821. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  82822. this._holes.forEach(function (hole) {
  82823. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  82824. });
  82825. }
  82826. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  82827. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  82828. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  82829. result.setIndices(indices);
  82830. return result;
  82831. };
  82832. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  82833. var StartIndex = positions.length / 3;
  82834. var ulength = 0;
  82835. for (var i = 0; i < points.elements.length; i++) {
  82836. var p = points.elements[i];
  82837. var p1;
  82838. if ((i + 1) > points.elements.length - 1) {
  82839. p1 = points.elements[0];
  82840. }
  82841. else {
  82842. p1 = points.elements[i + 1];
  82843. }
  82844. positions.push(p.x, 0, p.y);
  82845. positions.push(p.x, -depth, p.y);
  82846. positions.push(p1.x, 0, p1.y);
  82847. positions.push(p1.x, -depth, p1.y);
  82848. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  82849. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  82850. var v3 = v2.subtract(v1);
  82851. var v4 = new BABYLON.Vector3(0, 1, 0);
  82852. var vn = BABYLON.Vector3.Cross(v3, v4);
  82853. vn = vn.normalize();
  82854. uvs.push(ulength / bounds.width, 0);
  82855. uvs.push(ulength / bounds.width, 1);
  82856. ulength += v3.length();
  82857. uvs.push((ulength / bounds.width), 0);
  82858. uvs.push((ulength / bounds.width), 1);
  82859. if (!flip) {
  82860. normals.push(-vn.x, -vn.y, -vn.z);
  82861. normals.push(-vn.x, -vn.y, -vn.z);
  82862. normals.push(-vn.x, -vn.y, -vn.z);
  82863. normals.push(-vn.x, -vn.y, -vn.z);
  82864. indices.push(StartIndex);
  82865. indices.push(StartIndex + 1);
  82866. indices.push(StartIndex + 2);
  82867. indices.push(StartIndex + 1);
  82868. indices.push(StartIndex + 3);
  82869. indices.push(StartIndex + 2);
  82870. }
  82871. else {
  82872. normals.push(vn.x, vn.y, vn.z);
  82873. normals.push(vn.x, vn.y, vn.z);
  82874. normals.push(vn.x, vn.y, vn.z);
  82875. normals.push(vn.x, vn.y, vn.z);
  82876. indices.push(StartIndex);
  82877. indices.push(StartIndex + 2);
  82878. indices.push(StartIndex + 1);
  82879. indices.push(StartIndex + 1);
  82880. indices.push(StartIndex + 2);
  82881. indices.push(StartIndex + 3);
  82882. }
  82883. StartIndex += 4;
  82884. }
  82885. ;
  82886. };
  82887. return PolygonMeshBuilder;
  82888. }());
  82889. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  82890. })(BABYLON || (BABYLON = {}));
  82891. //# sourceMappingURL=babylon.polygonMesh.js.map
  82892. var BABYLON;
  82893. (function (BABYLON) {
  82894. // Unique ID when we import meshes from Babylon to CSG
  82895. var currentCSGMeshId = 0;
  82896. // # class Vertex
  82897. // Represents a vertex of a polygon. Use your own vertex class instead of this
  82898. // one to provide additional features like texture coordinates and vertex
  82899. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  82900. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  82901. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  82902. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  82903. // is not used anywhere else.
  82904. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  82905. var Vertex = /** @class */ (function () {
  82906. function Vertex(pos, normal, uv) {
  82907. this.pos = pos;
  82908. this.normal = normal;
  82909. this.uv = uv;
  82910. }
  82911. Vertex.prototype.clone = function () {
  82912. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  82913. };
  82914. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  82915. // orientation of a polygon is flipped.
  82916. Vertex.prototype.flip = function () {
  82917. this.normal = this.normal.scale(-1);
  82918. };
  82919. // Create a new vertex between this vertex and `other` by linearly
  82920. // interpolating all properties using a parameter of `t`. Subclasses should
  82921. // override this to interpolate additional properties.
  82922. Vertex.prototype.interpolate = function (other, t) {
  82923. 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));
  82924. };
  82925. return Vertex;
  82926. }());
  82927. // # class Plane
  82928. // Represents a plane in 3D space.
  82929. var Plane = /** @class */ (function () {
  82930. function Plane(normal, w) {
  82931. this.normal = normal;
  82932. this.w = w;
  82933. }
  82934. Plane.FromPoints = function (a, b, c) {
  82935. var v0 = c.subtract(a);
  82936. var v1 = b.subtract(a);
  82937. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  82938. return null;
  82939. }
  82940. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  82941. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  82942. };
  82943. Plane.prototype.clone = function () {
  82944. return new Plane(this.normal.clone(), this.w);
  82945. };
  82946. Plane.prototype.flip = function () {
  82947. this.normal.scaleInPlace(-1);
  82948. this.w = -this.w;
  82949. };
  82950. // Split `polygon` by this plane if needed, then put the polygon or polygon
  82951. // fragments in the appropriate lists. Coplanar polygons go into either
  82952. // `coplanarFront` or `coplanarBack` depending on their orientation with
  82953. // respect to this plane. Polygons in front or in back of this plane go into
  82954. // either `front` or `back`.
  82955. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  82956. var COPLANAR = 0;
  82957. var FRONT = 1;
  82958. var BACK = 2;
  82959. var SPANNING = 3;
  82960. // Classify each point as well as the entire polygon into one of the above
  82961. // four classes.
  82962. var polygonType = 0;
  82963. var types = [];
  82964. var i;
  82965. var t;
  82966. for (i = 0; i < polygon.vertices.length; i++) {
  82967. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  82968. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  82969. polygonType |= type;
  82970. types.push(type);
  82971. }
  82972. // Put the polygon in the correct list, splitting it when necessary.
  82973. switch (polygonType) {
  82974. case COPLANAR:
  82975. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  82976. break;
  82977. case FRONT:
  82978. front.push(polygon);
  82979. break;
  82980. case BACK:
  82981. back.push(polygon);
  82982. break;
  82983. case SPANNING:
  82984. var f = [], b = [];
  82985. for (i = 0; i < polygon.vertices.length; i++) {
  82986. var j = (i + 1) % polygon.vertices.length;
  82987. var ti = types[i], tj = types[j];
  82988. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  82989. if (ti !== BACK)
  82990. f.push(vi);
  82991. if (ti !== FRONT)
  82992. b.push(ti !== BACK ? vi.clone() : vi);
  82993. if ((ti | tj) === SPANNING) {
  82994. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  82995. var v = vi.interpolate(vj, t);
  82996. f.push(v);
  82997. b.push(v.clone());
  82998. }
  82999. }
  83000. var poly;
  83001. if (f.length >= 3) {
  83002. poly = new Polygon(f, polygon.shared);
  83003. if (poly.plane)
  83004. front.push(poly);
  83005. }
  83006. if (b.length >= 3) {
  83007. poly = new Polygon(b, polygon.shared);
  83008. if (poly.plane)
  83009. back.push(poly);
  83010. }
  83011. break;
  83012. }
  83013. };
  83014. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83015. // point is on the plane.
  83016. Plane.EPSILON = 1e-5;
  83017. return Plane;
  83018. }());
  83019. // # class Polygon
  83020. // Represents a convex polygon. The vertices used to initialize a polygon must
  83021. // be coplanar and form a convex loop.
  83022. //
  83023. // Each convex polygon has a `shared` property, which is shared between all
  83024. // polygons that are clones of each other or were split from the same polygon.
  83025. // This can be used to define per-polygon properties (such as surface color).
  83026. var Polygon = /** @class */ (function () {
  83027. function Polygon(vertices, shared) {
  83028. this.vertices = vertices;
  83029. this.shared = shared;
  83030. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83031. }
  83032. Polygon.prototype.clone = function () {
  83033. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83034. return new Polygon(vertices, this.shared);
  83035. };
  83036. Polygon.prototype.flip = function () {
  83037. this.vertices.reverse().map(function (v) { v.flip(); });
  83038. this.plane.flip();
  83039. };
  83040. return Polygon;
  83041. }());
  83042. // # class Node
  83043. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83044. // by picking a polygon to split along. That polygon (and all other coplanar
  83045. // polygons) are added directly to that node and the other polygons are added to
  83046. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83047. // no distinction between internal and leaf nodes.
  83048. var Node = /** @class */ (function () {
  83049. function Node(polygons) {
  83050. this.plane = null;
  83051. this.front = null;
  83052. this.back = null;
  83053. this.polygons = new Array();
  83054. if (polygons) {
  83055. this.build(polygons);
  83056. }
  83057. }
  83058. Node.prototype.clone = function () {
  83059. var node = new Node();
  83060. node.plane = this.plane && this.plane.clone();
  83061. node.front = this.front && this.front.clone();
  83062. node.back = this.back && this.back.clone();
  83063. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83064. return node;
  83065. };
  83066. // Convert solid space to empty space and empty space to solid space.
  83067. Node.prototype.invert = function () {
  83068. for (var i = 0; i < this.polygons.length; i++) {
  83069. this.polygons[i].flip();
  83070. }
  83071. if (this.plane) {
  83072. this.plane.flip();
  83073. }
  83074. if (this.front) {
  83075. this.front.invert();
  83076. }
  83077. if (this.back) {
  83078. this.back.invert();
  83079. }
  83080. var temp = this.front;
  83081. this.front = this.back;
  83082. this.back = temp;
  83083. };
  83084. // Recursively remove all polygons in `polygons` that are inside this BSP
  83085. // tree.
  83086. Node.prototype.clipPolygons = function (polygons) {
  83087. if (!this.plane)
  83088. return polygons.slice();
  83089. var front = new Array(), back = new Array();
  83090. for (var i = 0; i < polygons.length; i++) {
  83091. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83092. }
  83093. if (this.front) {
  83094. front = this.front.clipPolygons(front);
  83095. }
  83096. if (this.back) {
  83097. back = this.back.clipPolygons(back);
  83098. }
  83099. else {
  83100. back = [];
  83101. }
  83102. return front.concat(back);
  83103. };
  83104. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83105. // `bsp`.
  83106. Node.prototype.clipTo = function (bsp) {
  83107. this.polygons = bsp.clipPolygons(this.polygons);
  83108. if (this.front)
  83109. this.front.clipTo(bsp);
  83110. if (this.back)
  83111. this.back.clipTo(bsp);
  83112. };
  83113. // Return a list of all polygons in this BSP tree.
  83114. Node.prototype.allPolygons = function () {
  83115. var polygons = this.polygons.slice();
  83116. if (this.front)
  83117. polygons = polygons.concat(this.front.allPolygons());
  83118. if (this.back)
  83119. polygons = polygons.concat(this.back.allPolygons());
  83120. return polygons;
  83121. };
  83122. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83123. // new polygons are filtered down to the bottom of the tree and become new
  83124. // nodes there. Each set of polygons is partitioned using the first polygon
  83125. // (no heuristic is used to pick a good split).
  83126. Node.prototype.build = function (polygons) {
  83127. if (!polygons.length)
  83128. return;
  83129. if (!this.plane)
  83130. this.plane = polygons[0].plane.clone();
  83131. var front = new Array(), back = new Array();
  83132. for (var i = 0; i < polygons.length; i++) {
  83133. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83134. }
  83135. if (front.length) {
  83136. if (!this.front)
  83137. this.front = new Node();
  83138. this.front.build(front);
  83139. }
  83140. if (back.length) {
  83141. if (!this.back)
  83142. this.back = new Node();
  83143. this.back.build(back);
  83144. }
  83145. };
  83146. return Node;
  83147. }());
  83148. var CSG = /** @class */ (function () {
  83149. function CSG() {
  83150. this.polygons = new Array();
  83151. }
  83152. // Convert BABYLON.Mesh to BABYLON.CSG
  83153. CSG.FromMesh = function (mesh) {
  83154. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83155. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83156. if (mesh instanceof BABYLON.Mesh) {
  83157. mesh.computeWorldMatrix(true);
  83158. matrix = mesh.getWorldMatrix();
  83159. meshPosition = mesh.position.clone();
  83160. meshRotation = mesh.rotation.clone();
  83161. if (mesh.rotationQuaternion) {
  83162. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83163. }
  83164. meshScaling = mesh.scaling.clone();
  83165. }
  83166. else {
  83167. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83168. }
  83169. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83170. var subMeshes = mesh.subMeshes;
  83171. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83172. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83173. vertices = [];
  83174. for (var j = 0; j < 3; j++) {
  83175. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83176. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83177. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83178. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83179. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83180. vertex = new Vertex(position, normal, uv);
  83181. vertices.push(vertex);
  83182. }
  83183. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83184. // To handle the case of degenerated triangle
  83185. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83186. if (polygon.plane)
  83187. polygons.push(polygon);
  83188. }
  83189. }
  83190. var csg = CSG.FromPolygons(polygons);
  83191. csg.matrix = matrix;
  83192. csg.position = meshPosition;
  83193. csg.rotation = meshRotation;
  83194. csg.scaling = meshScaling;
  83195. csg.rotationQuaternion = meshRotationQuaternion;
  83196. currentCSGMeshId++;
  83197. return csg;
  83198. };
  83199. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83200. CSG.FromPolygons = function (polygons) {
  83201. var csg = new CSG();
  83202. csg.polygons = polygons;
  83203. return csg;
  83204. };
  83205. CSG.prototype.clone = function () {
  83206. var csg = new CSG();
  83207. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83208. csg.copyTransformAttributes(this);
  83209. return csg;
  83210. };
  83211. CSG.prototype.union = function (csg) {
  83212. var a = new Node(this.clone().polygons);
  83213. var b = new Node(csg.clone().polygons);
  83214. a.clipTo(b);
  83215. b.clipTo(a);
  83216. b.invert();
  83217. b.clipTo(a);
  83218. b.invert();
  83219. a.build(b.allPolygons());
  83220. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83221. };
  83222. CSG.prototype.unionInPlace = function (csg) {
  83223. var a = new Node(this.polygons);
  83224. var b = new Node(csg.polygons);
  83225. a.clipTo(b);
  83226. b.clipTo(a);
  83227. b.invert();
  83228. b.clipTo(a);
  83229. b.invert();
  83230. a.build(b.allPolygons());
  83231. this.polygons = a.allPolygons();
  83232. };
  83233. CSG.prototype.subtract = function (csg) {
  83234. var a = new Node(this.clone().polygons);
  83235. var b = new Node(csg.clone().polygons);
  83236. a.invert();
  83237. a.clipTo(b);
  83238. b.clipTo(a);
  83239. b.invert();
  83240. b.clipTo(a);
  83241. b.invert();
  83242. a.build(b.allPolygons());
  83243. a.invert();
  83244. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83245. };
  83246. CSG.prototype.subtractInPlace = function (csg) {
  83247. var a = new Node(this.polygons);
  83248. var b = new Node(csg.polygons);
  83249. a.invert();
  83250. a.clipTo(b);
  83251. b.clipTo(a);
  83252. b.invert();
  83253. b.clipTo(a);
  83254. b.invert();
  83255. a.build(b.allPolygons());
  83256. a.invert();
  83257. this.polygons = a.allPolygons();
  83258. };
  83259. CSG.prototype.intersect = function (csg) {
  83260. var a = new Node(this.clone().polygons);
  83261. var b = new Node(csg.clone().polygons);
  83262. a.invert();
  83263. b.clipTo(a);
  83264. b.invert();
  83265. a.clipTo(b);
  83266. b.clipTo(a);
  83267. a.build(b.allPolygons());
  83268. a.invert();
  83269. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83270. };
  83271. CSG.prototype.intersectInPlace = function (csg) {
  83272. var a = new Node(this.polygons);
  83273. var b = new Node(csg.polygons);
  83274. a.invert();
  83275. b.clipTo(a);
  83276. b.invert();
  83277. a.clipTo(b);
  83278. b.clipTo(a);
  83279. a.build(b.allPolygons());
  83280. a.invert();
  83281. this.polygons = a.allPolygons();
  83282. };
  83283. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83284. // not modified.
  83285. CSG.prototype.inverse = function () {
  83286. var csg = this.clone();
  83287. csg.inverseInPlace();
  83288. return csg;
  83289. };
  83290. CSG.prototype.inverseInPlace = function () {
  83291. this.polygons.map(function (p) { p.flip(); });
  83292. };
  83293. // This is used to keep meshes transformations so they can be restored
  83294. // when we build back a Babylon Mesh
  83295. // NB : All CSG operations are performed in world coordinates
  83296. CSG.prototype.copyTransformAttributes = function (csg) {
  83297. this.matrix = csg.matrix;
  83298. this.position = csg.position;
  83299. this.rotation = csg.rotation;
  83300. this.scaling = csg.scaling;
  83301. this.rotationQuaternion = csg.rotationQuaternion;
  83302. return this;
  83303. };
  83304. // Build Raw mesh from CSG
  83305. // Coordinates here are in world space
  83306. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83307. var matrix = this.matrix.clone();
  83308. matrix.invert();
  83309. 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;
  83310. if (keepSubMeshes) {
  83311. // Sort Polygons, since subMeshes are indices range
  83312. polygons.sort(function (a, b) {
  83313. if (a.shared.meshId === b.shared.meshId) {
  83314. return a.shared.subMeshId - b.shared.subMeshId;
  83315. }
  83316. else {
  83317. return a.shared.meshId - b.shared.meshId;
  83318. }
  83319. });
  83320. }
  83321. for (var i = 0, il = polygons.length; i < il; i++) {
  83322. polygon = polygons[i];
  83323. // Building SubMeshes
  83324. if (!subMesh_dict[polygon.shared.meshId]) {
  83325. subMesh_dict[polygon.shared.meshId] = {};
  83326. }
  83327. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83328. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83329. indexStart: +Infinity,
  83330. indexEnd: -Infinity,
  83331. materialIndex: polygon.shared.materialIndex
  83332. };
  83333. }
  83334. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83335. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83336. polygonIndices[0] = 0;
  83337. polygonIndices[1] = j - 1;
  83338. polygonIndices[2] = j;
  83339. for (var k = 0; k < 3; k++) {
  83340. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83341. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83342. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83343. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83344. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83345. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83346. // Check if 2 points can be merged
  83347. if (!(typeof vertex_idx !== 'undefined' &&
  83348. normals[vertex_idx * 3] === localNormal.x &&
  83349. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83350. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83351. uvs[vertex_idx * 2] === uv.x &&
  83352. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83353. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83354. uvs.push(uv.x, uv.y);
  83355. normals.push(normal.x, normal.y, normal.z);
  83356. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83357. }
  83358. indices.push(vertex_idx);
  83359. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83360. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83361. currentIndex++;
  83362. }
  83363. }
  83364. }
  83365. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83366. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83367. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83368. mesh.setIndices(indices, null);
  83369. if (keepSubMeshes) {
  83370. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83371. var materialIndexOffset = 0, materialMaxIndex;
  83372. mesh.subMeshes = new Array();
  83373. for (var m in subMesh_dict) {
  83374. materialMaxIndex = -1;
  83375. for (var sm in subMesh_dict[m]) {
  83376. subMesh_obj = subMesh_dict[m][sm];
  83377. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83378. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83379. }
  83380. materialIndexOffset += ++materialMaxIndex;
  83381. }
  83382. }
  83383. return mesh;
  83384. };
  83385. // Build Mesh from CSG taking material and transforms into account
  83386. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83387. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83388. mesh.material = material;
  83389. mesh.position.copyFrom(this.position);
  83390. mesh.rotation.copyFrom(this.rotation);
  83391. if (this.rotationQuaternion) {
  83392. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83393. }
  83394. mesh.scaling.copyFrom(this.scaling);
  83395. mesh.computeWorldMatrix(true);
  83396. return mesh;
  83397. };
  83398. return CSG;
  83399. }());
  83400. BABYLON.CSG = CSG;
  83401. })(BABYLON || (BABYLON = {}));
  83402. //# sourceMappingURL=babylon.csg.js.map
  83403. var BABYLON;
  83404. (function (BABYLON) {
  83405. var LensFlare = /** @class */ (function () {
  83406. function LensFlare(size, position, color, imgUrl, system) {
  83407. this.size = size;
  83408. this.position = position;
  83409. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83410. this.color = color || new BABYLON.Color3(1, 1, 1);
  83411. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83412. this._system = system;
  83413. system.lensFlares.push(this);
  83414. }
  83415. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83416. return new LensFlare(size, position, color, imgUrl, system);
  83417. };
  83418. LensFlare.prototype.dispose = function () {
  83419. if (this.texture) {
  83420. this.texture.dispose();
  83421. }
  83422. // Remove from scene
  83423. var index = this._system.lensFlares.indexOf(this);
  83424. this._system.lensFlares.splice(index, 1);
  83425. };
  83426. ;
  83427. return LensFlare;
  83428. }());
  83429. BABYLON.LensFlare = LensFlare;
  83430. })(BABYLON || (BABYLON = {}));
  83431. //# sourceMappingURL=babylon.lensFlare.js.map
  83432. var BABYLON;
  83433. (function (BABYLON) {
  83434. var LensFlareSystem = /** @class */ (function () {
  83435. function LensFlareSystem(name, emitter, scene) {
  83436. this.name = name;
  83437. this.lensFlares = new Array();
  83438. this.borderLimit = 300;
  83439. this.viewportBorder = 0;
  83440. this.layerMask = 0x0FFFFFFF;
  83441. this._vertexBuffers = {};
  83442. this._isEnabled = true;
  83443. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83444. this._emitter = emitter;
  83445. this.id = name;
  83446. scene.lensFlareSystems.push(this);
  83447. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83448. var engine = scene.getEngine();
  83449. // VBO
  83450. var vertices = [];
  83451. vertices.push(1, 1);
  83452. vertices.push(-1, 1);
  83453. vertices.push(-1, -1);
  83454. vertices.push(1, -1);
  83455. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83456. // Indices
  83457. var indices = [];
  83458. indices.push(0);
  83459. indices.push(1);
  83460. indices.push(2);
  83461. indices.push(0);
  83462. indices.push(2);
  83463. indices.push(3);
  83464. this._indexBuffer = engine.createIndexBuffer(indices);
  83465. // Effects
  83466. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83467. }
  83468. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83469. get: function () {
  83470. return this._isEnabled;
  83471. },
  83472. set: function (value) {
  83473. this._isEnabled = value;
  83474. },
  83475. enumerable: true,
  83476. configurable: true
  83477. });
  83478. LensFlareSystem.prototype.getScene = function () {
  83479. return this._scene;
  83480. };
  83481. LensFlareSystem.prototype.getEmitter = function () {
  83482. return this._emitter;
  83483. };
  83484. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83485. this._emitter = newEmitter;
  83486. };
  83487. LensFlareSystem.prototype.getEmitterPosition = function () {
  83488. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83489. };
  83490. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83491. var position = this.getEmitterPosition();
  83492. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83493. this._positionX = position.x;
  83494. this._positionY = position.y;
  83495. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83496. if (this.viewportBorder > 0) {
  83497. globalViewport.x -= this.viewportBorder;
  83498. globalViewport.y -= this.viewportBorder;
  83499. globalViewport.width += this.viewportBorder * 2;
  83500. globalViewport.height += this.viewportBorder * 2;
  83501. position.x += this.viewportBorder;
  83502. position.y += this.viewportBorder;
  83503. this._positionX += this.viewportBorder;
  83504. this._positionY += this.viewportBorder;
  83505. }
  83506. if (position.z > 0) {
  83507. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83508. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83509. return true;
  83510. }
  83511. return true;
  83512. }
  83513. return false;
  83514. };
  83515. LensFlareSystem.prototype._isVisible = function () {
  83516. if (!this._isEnabled || !this._scene.activeCamera) {
  83517. return false;
  83518. }
  83519. var emitterPosition = this.getEmitterPosition();
  83520. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83521. var distance = direction.length();
  83522. direction.normalize();
  83523. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83524. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83525. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83526. };
  83527. LensFlareSystem.prototype.render = function () {
  83528. if (!this._effect.isReady() || !this._scene.activeCamera)
  83529. return false;
  83530. var engine = this._scene.getEngine();
  83531. var viewport = this._scene.activeCamera.viewport;
  83532. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83533. // Position
  83534. if (!this.computeEffectivePosition(globalViewport)) {
  83535. return false;
  83536. }
  83537. // Visibility
  83538. if (!this._isVisible()) {
  83539. return false;
  83540. }
  83541. // Intensity
  83542. var awayX;
  83543. var awayY;
  83544. if (this._positionX < this.borderLimit + globalViewport.x) {
  83545. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83546. }
  83547. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83548. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83549. }
  83550. else {
  83551. awayX = 0;
  83552. }
  83553. if (this._positionY < this.borderLimit + globalViewport.y) {
  83554. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83555. }
  83556. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83557. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83558. }
  83559. else {
  83560. awayY = 0;
  83561. }
  83562. var away = (awayX > awayY) ? awayX : awayY;
  83563. away -= this.viewportBorder;
  83564. if (away > this.borderLimit) {
  83565. away = this.borderLimit;
  83566. }
  83567. var intensity = 1.0 - (away / this.borderLimit);
  83568. if (intensity < 0) {
  83569. return false;
  83570. }
  83571. if (intensity > 1.0) {
  83572. intensity = 1.0;
  83573. }
  83574. if (this.viewportBorder > 0) {
  83575. globalViewport.x += this.viewportBorder;
  83576. globalViewport.y += this.viewportBorder;
  83577. globalViewport.width -= this.viewportBorder * 2;
  83578. globalViewport.height -= this.viewportBorder * 2;
  83579. this._positionX -= this.viewportBorder;
  83580. this._positionY -= this.viewportBorder;
  83581. }
  83582. // Position
  83583. var centerX = globalViewport.x + globalViewport.width / 2;
  83584. var centerY = globalViewport.y + globalViewport.height / 2;
  83585. var distX = centerX - this._positionX;
  83586. var distY = centerY - this._positionY;
  83587. // Effects
  83588. engine.enableEffect(this._effect);
  83589. engine.setState(false);
  83590. engine.setDepthBuffer(false);
  83591. // VBOs
  83592. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83593. // Flares
  83594. for (var index = 0; index < this.lensFlares.length; index++) {
  83595. var flare = this.lensFlares[index];
  83596. engine.setAlphaMode(flare.alphaMode);
  83597. var x = centerX - (distX * flare.position);
  83598. var y = centerY - (distY * flare.position);
  83599. var cw = flare.size;
  83600. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83601. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83602. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83603. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83604. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83605. // Texture
  83606. this._effect.setTexture("textureSampler", flare.texture);
  83607. // Color
  83608. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83609. // Draw order
  83610. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83611. }
  83612. engine.setDepthBuffer(true);
  83613. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83614. return true;
  83615. };
  83616. LensFlareSystem.prototype.dispose = function () {
  83617. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83618. if (vertexBuffer) {
  83619. vertexBuffer.dispose();
  83620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83621. }
  83622. if (this._indexBuffer) {
  83623. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83624. this._indexBuffer = null;
  83625. }
  83626. while (this.lensFlares.length) {
  83627. this.lensFlares[0].dispose();
  83628. }
  83629. // Remove from scene
  83630. var index = this._scene.lensFlareSystems.indexOf(this);
  83631. this._scene.lensFlareSystems.splice(index, 1);
  83632. };
  83633. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83634. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83635. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83636. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83637. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83638. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83639. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83640. var parsedFlare = parsedLensFlareSystem.flares[index];
  83641. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83642. }
  83643. return lensFlareSystem;
  83644. };
  83645. LensFlareSystem.prototype.serialize = function () {
  83646. var serializationObject = {};
  83647. serializationObject.id = this.id;
  83648. serializationObject.name = this.name;
  83649. serializationObject.emitterId = this.getEmitter().id;
  83650. serializationObject.borderLimit = this.borderLimit;
  83651. serializationObject.flares = [];
  83652. for (var index = 0; index < this.lensFlares.length; index++) {
  83653. var flare = this.lensFlares[index];
  83654. serializationObject.flares.push({
  83655. size: flare.size,
  83656. position: flare.position,
  83657. color: flare.color.asArray(),
  83658. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83659. });
  83660. }
  83661. return serializationObject;
  83662. };
  83663. return LensFlareSystem;
  83664. }());
  83665. BABYLON.LensFlareSystem = LensFlareSystem;
  83666. })(BABYLON || (BABYLON = {}));
  83667. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83668. var BABYLON;
  83669. (function (BABYLON) {
  83670. /**
  83671. * This is a holder class for the physics joint created by the physics plugin.
  83672. * It holds a set of functions to control the underlying joint.
  83673. */
  83674. var PhysicsJoint = /** @class */ (function () {
  83675. function PhysicsJoint(type, jointData) {
  83676. this.type = type;
  83677. this.jointData = jointData;
  83678. jointData.nativeParams = jointData.nativeParams || {};
  83679. }
  83680. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83681. get: function () {
  83682. return this._physicsJoint;
  83683. },
  83684. set: function (newJoint) {
  83685. if (this._physicsJoint) {
  83686. //remove from the wolrd
  83687. }
  83688. this._physicsJoint = newJoint;
  83689. },
  83690. enumerable: true,
  83691. configurable: true
  83692. });
  83693. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  83694. set: function (physicsPlugin) {
  83695. this._physicsPlugin = physicsPlugin;
  83696. },
  83697. enumerable: true,
  83698. configurable: true
  83699. });
  83700. /**
  83701. * Execute a function that is physics-plugin specific.
  83702. * @param {Function} func the function that will be executed.
  83703. * It accepts two parameters: the physics world and the physics joint.
  83704. */
  83705. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  83706. func(this._physicsPlugin.world, this._physicsJoint);
  83707. };
  83708. //TODO check if the native joints are the same
  83709. //Joint Types
  83710. PhysicsJoint.DistanceJoint = 0;
  83711. PhysicsJoint.HingeJoint = 1;
  83712. PhysicsJoint.BallAndSocketJoint = 2;
  83713. PhysicsJoint.WheelJoint = 3;
  83714. PhysicsJoint.SliderJoint = 4;
  83715. //OIMO
  83716. PhysicsJoint.PrismaticJoint = 5;
  83717. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  83718. PhysicsJoint.UniversalJoint = 6;
  83719. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  83720. //Cannon
  83721. //Similar to a Ball-Joint. Different in params
  83722. PhysicsJoint.PointToPointJoint = 8;
  83723. //Cannon only at the moment
  83724. PhysicsJoint.SpringJoint = 9;
  83725. PhysicsJoint.LockJoint = 10;
  83726. return PhysicsJoint;
  83727. }());
  83728. BABYLON.PhysicsJoint = PhysicsJoint;
  83729. /**
  83730. * A class representing a physics distance joint.
  83731. */
  83732. var DistanceJoint = /** @class */ (function (_super) {
  83733. __extends(DistanceJoint, _super);
  83734. function DistanceJoint(jointData) {
  83735. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  83736. }
  83737. /**
  83738. * Update the predefined distance.
  83739. */
  83740. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  83741. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  83742. };
  83743. return DistanceJoint;
  83744. }(PhysicsJoint));
  83745. BABYLON.DistanceJoint = DistanceJoint;
  83746. var MotorEnabledJoint = /** @class */ (function (_super) {
  83747. __extends(MotorEnabledJoint, _super);
  83748. function MotorEnabledJoint(type, jointData) {
  83749. return _super.call(this, type, jointData) || this;
  83750. }
  83751. /**
  83752. * Set the motor values.
  83753. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83754. * @param {number} force the force to apply
  83755. * @param {number} maxForce max force for this motor.
  83756. */
  83757. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  83758. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83759. };
  83760. /**
  83761. * Set the motor's limits.
  83762. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83763. */
  83764. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83765. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83766. };
  83767. return MotorEnabledJoint;
  83768. }(PhysicsJoint));
  83769. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  83770. /**
  83771. * This class represents a single hinge physics joint
  83772. */
  83773. var HingeJoint = /** @class */ (function (_super) {
  83774. __extends(HingeJoint, _super);
  83775. function HingeJoint(jointData) {
  83776. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  83777. }
  83778. /**
  83779. * Set the motor values.
  83780. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83781. * @param {number} force the force to apply
  83782. * @param {number} maxForce max force for this motor.
  83783. */
  83784. HingeJoint.prototype.setMotor = function (force, maxForce) {
  83785. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  83786. };
  83787. /**
  83788. * Set the motor's limits.
  83789. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83790. */
  83791. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  83792. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  83793. };
  83794. return HingeJoint;
  83795. }(MotorEnabledJoint));
  83796. BABYLON.HingeJoint = HingeJoint;
  83797. /**
  83798. * This class represents a dual hinge physics joint (same as wheel joint)
  83799. */
  83800. var Hinge2Joint = /** @class */ (function (_super) {
  83801. __extends(Hinge2Joint, _super);
  83802. function Hinge2Joint(jointData) {
  83803. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  83804. }
  83805. /**
  83806. * Set the motor values.
  83807. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83808. * @param {number} force the force to apply
  83809. * @param {number} maxForce max force for this motor.
  83810. * @param {motorIndex} the motor's index, 0 or 1.
  83811. */
  83812. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  83813. if (motorIndex === void 0) { motorIndex = 0; }
  83814. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  83815. };
  83816. /**
  83817. * Set the motor limits.
  83818. * Attention, this function is plugin specific. Engines won't react 100% the same.
  83819. * @param {number} upperLimit the upper limit
  83820. * @param {number} lowerLimit lower limit
  83821. * @param {motorIndex} the motor's index, 0 or 1.
  83822. */
  83823. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  83824. if (motorIndex === void 0) { motorIndex = 0; }
  83825. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  83826. };
  83827. return Hinge2Joint;
  83828. }(MotorEnabledJoint));
  83829. BABYLON.Hinge2Joint = Hinge2Joint;
  83830. })(BABYLON || (BABYLON = {}));
  83831. //# sourceMappingURL=babylon.physicsJoint.js.map
  83832. var BABYLON;
  83833. (function (BABYLON) {
  83834. var PhysicsImpostor = /** @class */ (function () {
  83835. function PhysicsImpostor(object, type, _options, _scene) {
  83836. if (_options === void 0) { _options = { mass: 0 }; }
  83837. var _this = this;
  83838. this.object = object;
  83839. this.type = type;
  83840. this._options = _options;
  83841. this._scene = _scene;
  83842. this._bodyUpdateRequired = false;
  83843. this._onBeforePhysicsStepCallbacks = new Array();
  83844. this._onAfterPhysicsStepCallbacks = new Array();
  83845. this._onPhysicsCollideCallbacks = [];
  83846. this._deltaPosition = BABYLON.Vector3.Zero();
  83847. this._isDisposed = false;
  83848. //temp variables for parent rotation calculations
  83849. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  83850. this._tmpQuat = new BABYLON.Quaternion();
  83851. this._tmpQuat2 = new BABYLON.Quaternion();
  83852. /**
  83853. * this function is executed by the physics engine.
  83854. */
  83855. this.beforeStep = function () {
  83856. if (!_this._physicsEngine) {
  83857. return;
  83858. }
  83859. _this.object.translate(_this._deltaPosition, -1);
  83860. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  83861. _this.object.computeWorldMatrix(false);
  83862. if (_this.object.parent && _this.object.rotationQuaternion) {
  83863. _this.getParentsRotation();
  83864. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  83865. }
  83866. else {
  83867. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  83868. }
  83869. if (!_this._options.disableBidirectionalTransformation) {
  83870. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  83871. }
  83872. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  83873. func(_this);
  83874. });
  83875. };
  83876. /**
  83877. * this function is executed by the physics engine.
  83878. */
  83879. this.afterStep = function () {
  83880. if (!_this._physicsEngine) {
  83881. return;
  83882. }
  83883. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  83884. func(_this);
  83885. });
  83886. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  83887. // object has now its world rotation. needs to be converted to local.
  83888. if (_this.object.parent && _this.object.rotationQuaternion) {
  83889. _this.getParentsRotation();
  83890. _this._tmpQuat.conjugateInPlace();
  83891. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  83892. }
  83893. // take the position set and make it the absolute position of this object.
  83894. _this.object.setAbsolutePosition(_this.object.position);
  83895. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  83896. _this.object.translate(_this._deltaPosition, 1);
  83897. };
  83898. /**
  83899. * Legacy collision detection event support
  83900. */
  83901. this.onCollideEvent = null;
  83902. //event and body object due to cannon's event-based architecture.
  83903. this.onCollide = function (e) {
  83904. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  83905. return;
  83906. }
  83907. if (!_this._physicsEngine) {
  83908. return;
  83909. }
  83910. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  83911. if (otherImpostor) {
  83912. // Legacy collision detection event support
  83913. if (_this.onCollideEvent) {
  83914. _this.onCollideEvent(_this, otherImpostor);
  83915. }
  83916. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  83917. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  83918. }).forEach(function (obj) {
  83919. obj.callback(_this, otherImpostor);
  83920. });
  83921. }
  83922. };
  83923. //sanity check!
  83924. if (!this.object) {
  83925. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  83926. return;
  83927. }
  83928. //legacy support for old syntax.
  83929. if (!this._scene && object.getScene) {
  83930. this._scene = object.getScene();
  83931. }
  83932. if (!this._scene) {
  83933. return;
  83934. }
  83935. this._physicsEngine = this._scene.getPhysicsEngine();
  83936. if (!this._physicsEngine) {
  83937. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  83938. }
  83939. else {
  83940. //set the object's quaternion, if not set
  83941. if (!this.object.rotationQuaternion) {
  83942. if (this.object.rotation) {
  83943. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  83944. }
  83945. else {
  83946. this.object.rotationQuaternion = new BABYLON.Quaternion();
  83947. }
  83948. }
  83949. //default options params
  83950. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  83951. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  83952. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  83953. this._joints = [];
  83954. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  83955. if (!this.object.parent || this._options.ignoreParent) {
  83956. this._init();
  83957. }
  83958. else if (this.object.parent.physicsImpostor) {
  83959. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  83960. }
  83961. }
  83962. }
  83963. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  83964. get: function () {
  83965. return this._isDisposed;
  83966. },
  83967. enumerable: true,
  83968. configurable: true
  83969. });
  83970. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  83971. get: function () {
  83972. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  83973. },
  83974. set: function (value) {
  83975. this.setMass(value);
  83976. },
  83977. enumerable: true,
  83978. configurable: true
  83979. });
  83980. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  83981. get: function () {
  83982. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  83983. },
  83984. set: function (value) {
  83985. if (!this._physicsEngine) {
  83986. return;
  83987. }
  83988. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  83989. },
  83990. enumerable: true,
  83991. configurable: true
  83992. });
  83993. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  83994. get: function () {
  83995. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  83996. },
  83997. set: function (value) {
  83998. if (!this._physicsEngine) {
  83999. return;
  84000. }
  84001. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84002. },
  84003. enumerable: true,
  84004. configurable: true
  84005. });
  84006. /**
  84007. * This function will completly initialize this impostor.
  84008. * It will create a new body - but only if this mesh has no parent.
  84009. * If it has, this impostor will not be used other than to define the impostor
  84010. * of the child mesh.
  84011. */
  84012. PhysicsImpostor.prototype._init = function () {
  84013. if (!this._physicsEngine) {
  84014. return;
  84015. }
  84016. this._physicsEngine.removeImpostor(this);
  84017. this.physicsBody = null;
  84018. this._parent = this._parent || this._getPhysicsParent();
  84019. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84020. this._physicsEngine.addImpostor(this);
  84021. }
  84022. };
  84023. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84024. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84025. var parentMesh = this.object.parent;
  84026. return parentMesh.physicsImpostor;
  84027. }
  84028. return null;
  84029. };
  84030. /**
  84031. * Should a new body be generated.
  84032. */
  84033. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84034. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84035. };
  84036. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84037. this.forceUpdate();
  84038. };
  84039. /**
  84040. * Force a regeneration of this or the parent's impostor's body.
  84041. * Use under cautious - This will remove all joints already implemented.
  84042. */
  84043. PhysicsImpostor.prototype.forceUpdate = function () {
  84044. this._init();
  84045. if (this.parent && !this._options.ignoreParent) {
  84046. this.parent.forceUpdate();
  84047. }
  84048. };
  84049. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84050. /*public get mesh(): AbstractMesh {
  84051. return this._mesh;
  84052. }*/
  84053. /**
  84054. * Gets the body that holds this impostor. Either its own, or its parent.
  84055. */
  84056. get: function () {
  84057. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84058. },
  84059. /**
  84060. * Set the physics body. Used mainly by the physics engine/plugin
  84061. */
  84062. set: function (physicsBody) {
  84063. if (this._physicsBody && this._physicsEngine) {
  84064. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84065. }
  84066. this._physicsBody = physicsBody;
  84067. this.resetUpdateFlags();
  84068. },
  84069. enumerable: true,
  84070. configurable: true
  84071. });
  84072. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84073. get: function () {
  84074. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84075. },
  84076. set: function (value) {
  84077. this._parent = value;
  84078. },
  84079. enumerable: true,
  84080. configurable: true
  84081. });
  84082. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84083. this._bodyUpdateRequired = false;
  84084. };
  84085. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84086. if (this.object.getBoundingInfo) {
  84087. var q = this.object.rotationQuaternion;
  84088. //reset rotation
  84089. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84090. //calculate the world matrix with no rotation
  84091. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84092. var boundingInfo = this.object.getBoundingInfo();
  84093. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84094. //bring back the rotation
  84095. this.object.rotationQuaternion = q;
  84096. //calculate the world matrix with the new rotation
  84097. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84098. return size;
  84099. }
  84100. else {
  84101. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84102. }
  84103. };
  84104. PhysicsImpostor.prototype.getObjectCenter = function () {
  84105. if (this.object.getBoundingInfo) {
  84106. var boundingInfo = this.object.getBoundingInfo();
  84107. return boundingInfo.boundingBox.centerWorld;
  84108. }
  84109. else {
  84110. return this.object.position;
  84111. }
  84112. };
  84113. /**
  84114. * Get a specific parametes from the options parameter.
  84115. */
  84116. PhysicsImpostor.prototype.getParam = function (paramName) {
  84117. return this._options[paramName];
  84118. };
  84119. /**
  84120. * Sets a specific parameter in the options given to the physics plugin
  84121. */
  84122. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84123. this._options[paramName] = value;
  84124. this._bodyUpdateRequired = true;
  84125. };
  84126. /**
  84127. * Specifically change the body's mass option. Won't recreate the physics body object
  84128. */
  84129. PhysicsImpostor.prototype.setMass = function (mass) {
  84130. if (this.getParam("mass") !== mass) {
  84131. this.setParam("mass", mass);
  84132. }
  84133. if (this._physicsEngine) {
  84134. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84135. }
  84136. };
  84137. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84138. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84139. };
  84140. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84141. if (this._physicsEngine) {
  84142. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84143. }
  84144. };
  84145. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84146. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84147. };
  84148. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84149. if (this._physicsEngine) {
  84150. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84151. }
  84152. };
  84153. /**
  84154. * Execute a function with the physics plugin native code.
  84155. * Provide a function the will have two variables - the world object and the physics body object.
  84156. */
  84157. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84158. if (this._physicsEngine) {
  84159. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84160. }
  84161. };
  84162. /**
  84163. * Register a function that will be executed before the physics world is stepping forward.
  84164. */
  84165. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84166. this._onBeforePhysicsStepCallbacks.push(func);
  84167. };
  84168. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84169. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84170. if (index > -1) {
  84171. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84172. }
  84173. else {
  84174. BABYLON.Tools.Warn("Function to remove was not found");
  84175. }
  84176. };
  84177. /**
  84178. * Register a function that will be executed after the physics step
  84179. */
  84180. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84181. this._onAfterPhysicsStepCallbacks.push(func);
  84182. };
  84183. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84184. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84185. if (index > -1) {
  84186. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84187. }
  84188. else {
  84189. BABYLON.Tools.Warn("Function to remove was not found");
  84190. }
  84191. };
  84192. /**
  84193. * register a function that will be executed when this impostor collides against a different body.
  84194. */
  84195. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84196. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84197. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84198. };
  84199. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84200. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84201. var index = -1;
  84202. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84203. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84204. // chcek the arrays match
  84205. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84206. return collidedAgainstList.indexOf(impostor) > -1;
  84207. });
  84208. if (sameList) {
  84209. index = idx;
  84210. }
  84211. return sameList;
  84212. }
  84213. return false;
  84214. });
  84215. if (found) {
  84216. this._onPhysicsCollideCallbacks.splice(index, 1);
  84217. }
  84218. else {
  84219. BABYLON.Tools.Warn("Function to remove was not found");
  84220. }
  84221. };
  84222. PhysicsImpostor.prototype.getParentsRotation = function () {
  84223. var parent = this.object.parent;
  84224. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84225. while (parent) {
  84226. if (parent.rotationQuaternion) {
  84227. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84228. }
  84229. else {
  84230. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84231. }
  84232. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84233. parent = parent.parent;
  84234. }
  84235. return this._tmpQuat;
  84236. };
  84237. /**
  84238. * Apply a force
  84239. */
  84240. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84241. if (this._physicsEngine) {
  84242. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84243. }
  84244. return this;
  84245. };
  84246. /**
  84247. * Apply an impulse
  84248. */
  84249. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84250. if (this._physicsEngine) {
  84251. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84252. }
  84253. return this;
  84254. };
  84255. /**
  84256. * A help function to create a joint.
  84257. */
  84258. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84259. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84260. this.addJoint(otherImpostor, joint);
  84261. return this;
  84262. };
  84263. /**
  84264. * Add a joint to this impostor with a different impostor.
  84265. */
  84266. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84267. this._joints.push({
  84268. otherImpostor: otherImpostor,
  84269. joint: joint
  84270. });
  84271. if (this._physicsEngine) {
  84272. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84273. }
  84274. return this;
  84275. };
  84276. /**
  84277. * Will keep this body still, in a sleep mode.
  84278. */
  84279. PhysicsImpostor.prototype.sleep = function () {
  84280. if (this._physicsEngine) {
  84281. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84282. }
  84283. return this;
  84284. };
  84285. /**
  84286. * Wake the body up.
  84287. */
  84288. PhysicsImpostor.prototype.wakeUp = function () {
  84289. if (this._physicsEngine) {
  84290. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84291. }
  84292. return this;
  84293. };
  84294. PhysicsImpostor.prototype.clone = function (newObject) {
  84295. if (!newObject)
  84296. return null;
  84297. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84298. };
  84299. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84300. var _this = this;
  84301. //no dispose if no physics engine is available.
  84302. if (!this._physicsEngine) {
  84303. return;
  84304. }
  84305. this._joints.forEach(function (j) {
  84306. if (_this._physicsEngine) {
  84307. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84308. }
  84309. });
  84310. //dispose the physics body
  84311. this._physicsEngine.removeImpostor(this);
  84312. if (this.parent) {
  84313. this.parent.forceUpdate();
  84314. }
  84315. else {
  84316. /*this._object.getChildMeshes().forEach(function(mesh) {
  84317. if (mesh.physicsImpostor) {
  84318. if (disposeChildren) {
  84319. mesh.physicsImpostor.dispose();
  84320. mesh.physicsImpostor = null;
  84321. }
  84322. }
  84323. })*/
  84324. }
  84325. this._isDisposed = true;
  84326. };
  84327. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84328. this._deltaPosition.copyFrom(position);
  84329. };
  84330. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84331. if (!this._deltaRotation) {
  84332. this._deltaRotation = new BABYLON.Quaternion();
  84333. }
  84334. this._deltaRotation.copyFrom(rotation);
  84335. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84336. };
  84337. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84338. if (this._physicsEngine) {
  84339. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84340. }
  84341. return this;
  84342. };
  84343. PhysicsImpostor.prototype.getRadius = function () {
  84344. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84345. };
  84346. /**
  84347. * Sync a bone with this impostor
  84348. * @param bone The bone to sync to the impostor.
  84349. * @param boneMesh The mesh that the bone is influencing.
  84350. * @param jointPivot The pivot of the joint / bone in local space.
  84351. * @param distToJoint Optional distance from the impostor to the joint.
  84352. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84353. */
  84354. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84355. var tempVec = PhysicsImpostor._tmpVecs[0];
  84356. var mesh = this.object;
  84357. if (mesh.rotationQuaternion) {
  84358. if (adjustRotation) {
  84359. var tempQuat = PhysicsImpostor._tmpQuat;
  84360. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84361. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84362. }
  84363. else {
  84364. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84365. }
  84366. }
  84367. tempVec.x = 0;
  84368. tempVec.y = 0;
  84369. tempVec.z = 0;
  84370. if (jointPivot) {
  84371. tempVec.x = jointPivot.x;
  84372. tempVec.y = jointPivot.y;
  84373. tempVec.z = jointPivot.z;
  84374. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84375. if (distToJoint === undefined || distToJoint === null) {
  84376. distToJoint = jointPivot.length();
  84377. }
  84378. tempVec.x *= distToJoint;
  84379. tempVec.y *= distToJoint;
  84380. tempVec.z *= distToJoint;
  84381. }
  84382. if (bone.getParent()) {
  84383. tempVec.addInPlace(mesh.getAbsolutePosition());
  84384. bone.setAbsolutePosition(tempVec, boneMesh);
  84385. }
  84386. else {
  84387. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84388. boneMesh.position.x -= tempVec.x;
  84389. boneMesh.position.y -= tempVec.y;
  84390. boneMesh.position.z -= tempVec.z;
  84391. }
  84392. };
  84393. /**
  84394. * Sync impostor to a bone
  84395. * @param bone The bone that the impostor will be synced to.
  84396. * @param boneMesh The mesh that the bone is influencing.
  84397. * @param jointPivot The pivot of the joint / bone in local space.
  84398. * @param distToJoint Optional distance from the impostor to the joint.
  84399. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84400. * @param boneAxis Optional vector3 axis the bone is aligned with
  84401. */
  84402. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84403. var mesh = this.object;
  84404. if (mesh.rotationQuaternion) {
  84405. if (adjustRotation) {
  84406. var tempQuat = PhysicsImpostor._tmpQuat;
  84407. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84408. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84409. }
  84410. else {
  84411. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84412. }
  84413. }
  84414. var pos = PhysicsImpostor._tmpVecs[0];
  84415. var boneDir = PhysicsImpostor._tmpVecs[1];
  84416. if (!boneAxis) {
  84417. boneAxis = PhysicsImpostor._tmpVecs[2];
  84418. boneAxis.x = 0;
  84419. boneAxis.y = 1;
  84420. boneAxis.z = 0;
  84421. }
  84422. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84423. bone.getAbsolutePositionToRef(boneMesh, pos);
  84424. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84425. distToJoint = jointPivot.length();
  84426. }
  84427. if (distToJoint !== undefined && distToJoint !== null) {
  84428. pos.x += boneDir.x * distToJoint;
  84429. pos.y += boneDir.y * distToJoint;
  84430. pos.z += boneDir.z * distToJoint;
  84431. }
  84432. mesh.setAbsolutePosition(pos);
  84433. };
  84434. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84435. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84436. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84437. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84438. //Impostor types
  84439. PhysicsImpostor.NoImpostor = 0;
  84440. PhysicsImpostor.SphereImpostor = 1;
  84441. PhysicsImpostor.BoxImpostor = 2;
  84442. PhysicsImpostor.PlaneImpostor = 3;
  84443. PhysicsImpostor.MeshImpostor = 4;
  84444. PhysicsImpostor.CylinderImpostor = 7;
  84445. PhysicsImpostor.ParticleImpostor = 8;
  84446. PhysicsImpostor.HeightmapImpostor = 9;
  84447. return PhysicsImpostor;
  84448. }());
  84449. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84450. })(BABYLON || (BABYLON = {}));
  84451. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84452. var BABYLON;
  84453. (function (BABYLON) {
  84454. var PhysicsEngine = /** @class */ (function () {
  84455. function PhysicsEngine(gravity, _physicsPlugin) {
  84456. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84457. this._physicsPlugin = _physicsPlugin;
  84458. //new methods and parameters
  84459. this._impostors = [];
  84460. this._joints = [];
  84461. if (!this._physicsPlugin.isSupported()) {
  84462. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84463. + "Please make sure it is included.");
  84464. }
  84465. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84466. this.setGravity(gravity);
  84467. this.setTimeStep();
  84468. }
  84469. PhysicsEngine.prototype.setGravity = function (gravity) {
  84470. this.gravity = gravity;
  84471. this._physicsPlugin.setGravity(this.gravity);
  84472. };
  84473. /**
  84474. * Set the time step of the physics engine.
  84475. * default is 1/60.
  84476. * To slow it down, enter 1/600 for example.
  84477. * To speed it up, 1/30
  84478. * @param {number} newTimeStep the new timestep to apply to this world.
  84479. */
  84480. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84481. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84482. this._physicsPlugin.setTimeStep(newTimeStep);
  84483. };
  84484. /**
  84485. * Get the time step of the physics engine.
  84486. */
  84487. PhysicsEngine.prototype.getTimeStep = function () {
  84488. return this._physicsPlugin.getTimeStep();
  84489. };
  84490. PhysicsEngine.prototype.dispose = function () {
  84491. this._impostors.forEach(function (impostor) {
  84492. impostor.dispose();
  84493. });
  84494. this._physicsPlugin.dispose();
  84495. };
  84496. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84497. return this._physicsPlugin.name;
  84498. };
  84499. /**
  84500. * Adding a new impostor for the impostor tracking.
  84501. * This will be done by the impostor itself.
  84502. * @param {PhysicsImpostor} impostor the impostor to add
  84503. */
  84504. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84505. impostor.uniqueId = this._impostors.push(impostor);
  84506. //if no parent, generate the body
  84507. if (!impostor.parent) {
  84508. this._physicsPlugin.generatePhysicsBody(impostor);
  84509. }
  84510. };
  84511. /**
  84512. * Remove an impostor from the engine.
  84513. * This impostor and its mesh will not longer be updated by the physics engine.
  84514. * @param {PhysicsImpostor} impostor the impostor to remove
  84515. */
  84516. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84517. var index = this._impostors.indexOf(impostor);
  84518. if (index > -1) {
  84519. var removed = this._impostors.splice(index, 1);
  84520. //Is it needed?
  84521. if (removed.length) {
  84522. //this will also remove it from the world.
  84523. removed[0].physicsBody = null;
  84524. }
  84525. }
  84526. };
  84527. /**
  84528. * Add a joint to the physics engine
  84529. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84530. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84531. * @param {PhysicsJoint} the joint that will connect both impostors.
  84532. */
  84533. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84534. var impostorJoint = {
  84535. mainImpostor: mainImpostor,
  84536. connectedImpostor: connectedImpostor,
  84537. joint: joint
  84538. };
  84539. joint.physicsPlugin = this._physicsPlugin;
  84540. this._joints.push(impostorJoint);
  84541. this._physicsPlugin.generateJoint(impostorJoint);
  84542. };
  84543. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84544. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84545. return (impostorJoint.connectedImpostor === connectedImpostor
  84546. && impostorJoint.joint === joint
  84547. && impostorJoint.mainImpostor === mainImpostor);
  84548. });
  84549. if (matchingJoints.length) {
  84550. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84551. //TODO remove it from the list as well
  84552. }
  84553. };
  84554. /**
  84555. * Called by the scene. no need to call it.
  84556. */
  84557. PhysicsEngine.prototype._step = function (delta) {
  84558. var _this = this;
  84559. //check if any mesh has no body / requires an update
  84560. this._impostors.forEach(function (impostor) {
  84561. if (impostor.isBodyInitRequired()) {
  84562. _this._physicsPlugin.generatePhysicsBody(impostor);
  84563. }
  84564. });
  84565. if (delta > 0.1) {
  84566. delta = 0.1;
  84567. }
  84568. else if (delta <= 0) {
  84569. delta = 1.0 / 60.0;
  84570. }
  84571. this._physicsPlugin.executeStep(delta, this._impostors);
  84572. };
  84573. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84574. return this._physicsPlugin;
  84575. };
  84576. PhysicsEngine.prototype.getImpostors = function () {
  84577. return this._impostors;
  84578. };
  84579. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84580. for (var i = 0; i < this._impostors.length; ++i) {
  84581. if (this._impostors[i].object === object) {
  84582. return this._impostors[i];
  84583. }
  84584. }
  84585. return null;
  84586. };
  84587. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84588. for (var i = 0; i < this._impostors.length; ++i) {
  84589. if (this._impostors[i].physicsBody === body) {
  84590. return this._impostors[i];
  84591. }
  84592. }
  84593. return null;
  84594. };
  84595. // Statics
  84596. PhysicsEngine.Epsilon = 0.001;
  84597. return PhysicsEngine;
  84598. }());
  84599. BABYLON.PhysicsEngine = PhysicsEngine;
  84600. })(BABYLON || (BABYLON = {}));
  84601. //# sourceMappingURL=babylon.physicsEngine.js.map
  84602. var BABYLON;
  84603. (function (BABYLON) {
  84604. var PhysicsHelper = /** @class */ (function () {
  84605. function PhysicsHelper(scene) {
  84606. this._scene = scene;
  84607. this._physicsEngine = this._scene.getPhysicsEngine();
  84608. if (!this._physicsEngine) {
  84609. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84610. }
  84611. }
  84612. /**
  84613. * @param {Vector3} origin the origin of the explosion
  84614. * @param {number} radius the explosion radius
  84615. * @param {number} strength the explosion strength
  84616. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84617. */
  84618. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84619. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84620. if (!this._physicsEngine) {
  84621. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84622. return null;
  84623. }
  84624. var impostors = this._physicsEngine.getImpostors();
  84625. if (impostors.length === 0) {
  84626. return null;
  84627. }
  84628. var event = new PhysicsRadialExplosionEvent(this._scene);
  84629. impostors.forEach(function (impostor) {
  84630. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84631. if (!impostorForceAndContactPoint) {
  84632. return;
  84633. }
  84634. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84635. });
  84636. event.dispose(false);
  84637. return event;
  84638. };
  84639. /**
  84640. * @param {Vector3} origin the origin of the explosion
  84641. * @param {number} radius the explosion radius
  84642. * @param {number} strength the explosion strength
  84643. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84644. */
  84645. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84646. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84647. if (!this._physicsEngine) {
  84648. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84649. return null;
  84650. }
  84651. var impostors = this._physicsEngine.getImpostors();
  84652. if (impostors.length === 0) {
  84653. return null;
  84654. }
  84655. var event = new PhysicsRadialExplosionEvent(this._scene);
  84656. impostors.forEach(function (impostor) {
  84657. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84658. if (!impostorForceAndContactPoint) {
  84659. return;
  84660. }
  84661. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84662. });
  84663. event.dispose(false);
  84664. return event;
  84665. };
  84666. /**
  84667. * @param {Vector3} origin the origin of the explosion
  84668. * @param {number} radius the explosion radius
  84669. * @param {number} strength the explosion strength
  84670. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84671. */
  84672. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84673. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84674. if (!this._physicsEngine) {
  84675. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84676. return null;
  84677. }
  84678. var impostors = this._physicsEngine.getImpostors();
  84679. if (impostors.length === 0) {
  84680. return null;
  84681. }
  84682. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84683. event.dispose(false);
  84684. return event;
  84685. };
  84686. /**
  84687. * @param {Vector3} origin the origin of the updraft
  84688. * @param {number} radius the radius of the updraft
  84689. * @param {number} strength the strength of the updraft
  84690. * @param {number} height the height of the updraft
  84691. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  84692. */
  84693. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  84694. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  84695. if (!this._physicsEngine) {
  84696. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84697. return null;
  84698. }
  84699. if (this._physicsEngine.getImpostors().length === 0) {
  84700. return null;
  84701. }
  84702. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  84703. event.dispose(false);
  84704. return event;
  84705. };
  84706. /**
  84707. * @param {Vector3} origin the of the vortex
  84708. * @param {number} radius the radius of the vortex
  84709. * @param {number} strength the strength of the vortex
  84710. * @param {number} height the height of the vortex
  84711. */
  84712. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  84713. if (!this._physicsEngine) {
  84714. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84715. return null;
  84716. }
  84717. if (this._physicsEngine.getImpostors().length === 0) {
  84718. return null;
  84719. }
  84720. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  84721. event.dispose(false);
  84722. return event;
  84723. };
  84724. return PhysicsHelper;
  84725. }());
  84726. BABYLON.PhysicsHelper = PhysicsHelper;
  84727. /***** Radial explosion *****/
  84728. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  84729. function PhysicsRadialExplosionEvent(scene) {
  84730. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  84731. this._rays = [];
  84732. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  84733. this._scene = scene;
  84734. }
  84735. /**
  84736. * Returns the data related to the radial explosion event (sphere & rays).
  84737. * @returns {PhysicsRadialExplosionEventData}
  84738. */
  84739. PhysicsRadialExplosionEvent.prototype.getData = function () {
  84740. this._dataFetched = true;
  84741. return {
  84742. sphere: this._sphere,
  84743. rays: this._rays,
  84744. };
  84745. };
  84746. /**
  84747. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  84748. * @param impostor
  84749. * @param {Vector3} origin the origin of the explosion
  84750. * @param {number} radius the explosion radius
  84751. * @param {number} strength the explosion strength
  84752. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  84753. * @returns {Nullable<PhysicsForceAndContactPoint>}
  84754. */
  84755. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  84756. if (impostor.mass === 0) {
  84757. return null;
  84758. }
  84759. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  84760. return null;
  84761. }
  84762. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  84763. return null;
  84764. }
  84765. var impostorObjectCenter = impostor.getObjectCenter();
  84766. var direction = impostorObjectCenter.subtract(origin);
  84767. var ray = new BABYLON.Ray(origin, direction, radius);
  84768. this._rays.push(ray);
  84769. var hit = ray.intersectsMesh(impostor.object);
  84770. var contactPoint = hit.pickedPoint;
  84771. if (!contactPoint) {
  84772. return null;
  84773. }
  84774. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  84775. if (distanceFromOrigin > radius) {
  84776. return null;
  84777. }
  84778. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  84779. ? strength
  84780. : strength * (1 - (distanceFromOrigin / radius));
  84781. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84782. return { force: force, contactPoint: contactPoint };
  84783. };
  84784. /**
  84785. * Disposes the sphere.
  84786. * @param {bolean} force
  84787. */
  84788. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  84789. var _this = this;
  84790. if (force === void 0) { force = true; }
  84791. if (force) {
  84792. this._sphere.dispose();
  84793. }
  84794. else {
  84795. setTimeout(function () {
  84796. if (!_this._dataFetched) {
  84797. _this._sphere.dispose();
  84798. }
  84799. }, 0);
  84800. }
  84801. };
  84802. /*** Helpers ***/
  84803. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  84804. if (!this._sphere) {
  84805. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  84806. this._sphere.isVisible = false;
  84807. }
  84808. };
  84809. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  84810. var impostorObject = impostor.object;
  84811. this._prepareSphere();
  84812. this._sphere.position = origin;
  84813. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  84814. this._sphere._updateBoundingInfo();
  84815. this._sphere.computeWorldMatrix(true);
  84816. return this._sphere.intersectsMesh(impostorObject, true);
  84817. };
  84818. return PhysicsRadialExplosionEvent;
  84819. }());
  84820. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  84821. /***** Gravitational Field *****/
  84822. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  84823. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  84824. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84825. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84826. this._physicsHelper = physicsHelper;
  84827. this._scene = scene;
  84828. this._origin = origin;
  84829. this._radius = radius;
  84830. this._strength = strength;
  84831. this._falloff = falloff;
  84832. this._tickCallback = this._tick.bind(this);
  84833. }
  84834. /**
  84835. * Returns the data related to the gravitational field event (sphere).
  84836. * @returns {PhysicsGravitationalFieldEventData}
  84837. */
  84838. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  84839. this._dataFetched = true;
  84840. return {
  84841. sphere: this._sphere,
  84842. };
  84843. };
  84844. /**
  84845. * Enables the gravitational field.
  84846. */
  84847. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  84848. this._tickCallback.call(this);
  84849. this._scene.registerBeforeRender(this._tickCallback);
  84850. };
  84851. /**
  84852. * Disables the gravitational field.
  84853. */
  84854. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  84855. this._scene.unregisterBeforeRender(this._tickCallback);
  84856. };
  84857. /**
  84858. * Disposes the sphere.
  84859. * @param {bolean} force
  84860. */
  84861. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  84862. var _this = this;
  84863. if (force === void 0) { force = true; }
  84864. if (force) {
  84865. this._sphere.dispose();
  84866. }
  84867. else {
  84868. setTimeout(function () {
  84869. if (!_this._dataFetched) {
  84870. _this._sphere.dispose();
  84871. }
  84872. }, 0);
  84873. }
  84874. };
  84875. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  84876. // Since the params won't change, we fetch the event only once
  84877. if (this._sphere) {
  84878. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84879. }
  84880. else {
  84881. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  84882. if (radialExplosionEvent) {
  84883. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  84884. }
  84885. }
  84886. };
  84887. return PhysicsGravitationalFieldEvent;
  84888. }());
  84889. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  84890. /***** Updraft *****/
  84891. var PhysicsUpdraftEvent = /** @class */ (function () {
  84892. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  84893. this._scene = _scene;
  84894. this._origin = _origin;
  84895. this._radius = _radius;
  84896. this._strength = _strength;
  84897. this._height = _height;
  84898. this._updraftMode = _updraftMode;
  84899. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  84900. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  84901. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  84902. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  84903. this._physicsEngine = this._scene.getPhysicsEngine();
  84904. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  84905. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  84906. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84907. this._originDirection = this._origin.subtract(this._originTop).normalize();
  84908. }
  84909. this._tickCallback = this._tick.bind(this);
  84910. }
  84911. /**
  84912. * Returns the data related to the updraft event (cylinder).
  84913. * @returns {PhysicsUpdraftEventData}
  84914. */
  84915. PhysicsUpdraftEvent.prototype.getData = function () {
  84916. this._dataFetched = true;
  84917. return {
  84918. cylinder: this._cylinder,
  84919. };
  84920. };
  84921. /**
  84922. * Enables the updraft.
  84923. */
  84924. PhysicsUpdraftEvent.prototype.enable = function () {
  84925. this._tickCallback.call(this);
  84926. this._scene.registerBeforeRender(this._tickCallback);
  84927. };
  84928. /**
  84929. * Disables the cortex.
  84930. */
  84931. PhysicsUpdraftEvent.prototype.disable = function () {
  84932. this._scene.unregisterBeforeRender(this._tickCallback);
  84933. };
  84934. /**
  84935. * Disposes the sphere.
  84936. * @param {bolean} force
  84937. */
  84938. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  84939. var _this = this;
  84940. if (force === void 0) { force = true; }
  84941. if (force) {
  84942. this._cylinder.dispose();
  84943. }
  84944. else {
  84945. setTimeout(function () {
  84946. if (!_this._dataFetched) {
  84947. _this._cylinder.dispose();
  84948. }
  84949. }, 0);
  84950. }
  84951. };
  84952. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  84953. if (impostor.mass === 0) {
  84954. return null;
  84955. }
  84956. if (!this._intersectsWithCylinder(impostor)) {
  84957. return null;
  84958. }
  84959. var impostorObjectCenter = impostor.getObjectCenter();
  84960. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  84961. var direction = this._originDirection;
  84962. }
  84963. else {
  84964. var direction = impostorObjectCenter.subtract(this._originTop);
  84965. }
  84966. var multiplier = this._strength * -1;
  84967. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  84968. return { force: force, contactPoint: impostorObjectCenter };
  84969. };
  84970. PhysicsUpdraftEvent.prototype._tick = function () {
  84971. var _this = this;
  84972. this._physicsEngine.getImpostors().forEach(function (impostor) {
  84973. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  84974. if (!impostorForceAndContactPoint) {
  84975. return;
  84976. }
  84977. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84978. });
  84979. };
  84980. /*** Helpers ***/
  84981. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  84982. if (!this._cylinder) {
  84983. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  84984. height: this._height,
  84985. diameter: this._radius * 2,
  84986. }, this._scene);
  84987. this._cylinder.isVisible = false;
  84988. }
  84989. };
  84990. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  84991. var impostorObject = impostor.object;
  84992. this._prepareCylinder();
  84993. this._cylinder.position = this._cylinderPosition;
  84994. return this._cylinder.intersectsMesh(impostorObject, true);
  84995. };
  84996. return PhysicsUpdraftEvent;
  84997. }());
  84998. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  84999. /***** Vortex *****/
  85000. var PhysicsVortexEvent = /** @class */ (function () {
  85001. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85002. this._scene = _scene;
  85003. this._origin = _origin;
  85004. this._radius = _radius;
  85005. this._strength = _strength;
  85006. this._height = _height;
  85007. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85008. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85009. this._updraftMultiplier = 0.02;
  85010. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85011. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85012. this._physicsEngine = this._scene.getPhysicsEngine();
  85013. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85014. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85015. this._tickCallback = this._tick.bind(this);
  85016. }
  85017. /**
  85018. * Returns the data related to the vortex event (cylinder).
  85019. * @returns {PhysicsVortexEventData}
  85020. */
  85021. PhysicsVortexEvent.prototype.getData = function () {
  85022. this._dataFetched = true;
  85023. return {
  85024. cylinder: this._cylinder,
  85025. };
  85026. };
  85027. /**
  85028. * Enables the vortex.
  85029. */
  85030. PhysicsVortexEvent.prototype.enable = function () {
  85031. this._tickCallback.call(this);
  85032. this._scene.registerBeforeRender(this._tickCallback);
  85033. };
  85034. /**
  85035. * Disables the cortex.
  85036. */
  85037. PhysicsVortexEvent.prototype.disable = function () {
  85038. this._scene.unregisterBeforeRender(this._tickCallback);
  85039. };
  85040. /**
  85041. * Disposes the sphere.
  85042. * @param {bolean} force
  85043. */
  85044. PhysicsVortexEvent.prototype.dispose = function (force) {
  85045. var _this = this;
  85046. if (force === void 0) { force = true; }
  85047. if (force) {
  85048. this._cylinder.dispose();
  85049. }
  85050. else {
  85051. setTimeout(function () {
  85052. if (!_this._dataFetched) {
  85053. _this._cylinder.dispose();
  85054. }
  85055. }, 0);
  85056. }
  85057. };
  85058. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85059. if (impostor.mass === 0) {
  85060. return null;
  85061. }
  85062. if (!this._intersectsWithCylinder(impostor)) {
  85063. return null;
  85064. }
  85065. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85066. return null;
  85067. }
  85068. var impostorObjectCenter = impostor.getObjectCenter();
  85069. 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)
  85070. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85071. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85072. var hit = ray.intersectsMesh(impostor.object);
  85073. var contactPoint = hit.pickedPoint;
  85074. if (!contactPoint) {
  85075. return null;
  85076. }
  85077. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85078. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85079. var directionToOrigin = contactPoint.normalize();
  85080. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85081. directionToOrigin = directionToOrigin.negate();
  85082. }
  85083. // TODO: find a more physically based solution
  85084. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85085. var forceX = directionToOrigin.x * this._strength / 8;
  85086. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85087. var forceZ = directionToOrigin.z * this._strength / 8;
  85088. }
  85089. else {
  85090. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85091. var forceY = this._originTop.y * this._updraftMultiplier;
  85092. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85093. }
  85094. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85095. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85096. return { force: force, contactPoint: impostorObjectCenter };
  85097. };
  85098. PhysicsVortexEvent.prototype._tick = function () {
  85099. var _this = this;
  85100. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85101. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85102. if (!impostorForceAndContactPoint) {
  85103. return;
  85104. }
  85105. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85106. });
  85107. };
  85108. /*** Helpers ***/
  85109. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85110. if (!this._cylinder) {
  85111. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85112. height: this._height,
  85113. diameter: this._radius * 2,
  85114. }, this._scene);
  85115. this._cylinder.isVisible = false;
  85116. }
  85117. };
  85118. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85119. var impostorObject = impostor.object;
  85120. this._prepareCylinder();
  85121. this._cylinder.position = this._cylinderPosition;
  85122. return this._cylinder.intersectsMesh(impostorObject, true);
  85123. };
  85124. return PhysicsVortexEvent;
  85125. }());
  85126. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85127. /***** Enums *****/
  85128. /**
  85129. * The strenght of the force in correspondence to the distance of the affected object
  85130. */
  85131. var PhysicsRadialImpulseFalloff;
  85132. (function (PhysicsRadialImpulseFalloff) {
  85133. /** Defines that impulse is constant in strength across it's whole radius */
  85134. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85135. /** DEfines that impulse gets weaker if it's further from the origin */
  85136. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85137. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85138. /**
  85139. * The strenght of the force in correspondence to the distance of the affected object
  85140. */
  85141. var PhysicsUpdraftMode;
  85142. (function (PhysicsUpdraftMode) {
  85143. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85144. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85145. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85146. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85147. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85148. })(BABYLON || (BABYLON = {}));
  85149. //# sourceMappingURL=babylon.physicsHelper.js.map
  85150. var BABYLON;
  85151. (function (BABYLON) {
  85152. var CannonJSPlugin = /** @class */ (function () {
  85153. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85154. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85155. if (iterations === void 0) { iterations = 10; }
  85156. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85157. this.name = "CannonJSPlugin";
  85158. this._physicsMaterials = new Array();
  85159. this._fixedTimeStep = 1 / 60;
  85160. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85161. this.BJSCANNON = CANNON;
  85162. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85163. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85164. this._tmpPosition = BABYLON.Vector3.Zero();
  85165. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85166. this._tmpUnityRotation = new BABYLON.Quaternion();
  85167. if (!this.isSupported()) {
  85168. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85169. return;
  85170. }
  85171. this._extendNamespace();
  85172. this.world = new this.BJSCANNON.World();
  85173. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85174. this.world.solver.iterations = iterations;
  85175. }
  85176. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85177. this.world.gravity.copy(gravity);
  85178. };
  85179. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85180. this._fixedTimeStep = timeStep;
  85181. };
  85182. CannonJSPlugin.prototype.getTimeStep = function () {
  85183. return this._fixedTimeStep;
  85184. };
  85185. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85186. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85187. };
  85188. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85189. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85190. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85191. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85192. };
  85193. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85194. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85195. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85196. impostor.physicsBody.applyForce(impulse, worldPoint);
  85197. };
  85198. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85199. //parent-child relationship. Does this impostor has a parent impostor?
  85200. if (impostor.parent) {
  85201. if (impostor.physicsBody) {
  85202. this.removePhysicsBody(impostor);
  85203. //TODO is that needed?
  85204. impostor.forceUpdate();
  85205. }
  85206. return;
  85207. }
  85208. //should a new body be created for this impostor?
  85209. if (impostor.isBodyInitRequired()) {
  85210. var shape = this._createShape(impostor);
  85211. //unregister events, if body is being changed
  85212. var oldBody = impostor.physicsBody;
  85213. if (oldBody) {
  85214. this.removePhysicsBody(impostor);
  85215. }
  85216. //create the body and material
  85217. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85218. var bodyCreationObject = {
  85219. mass: impostor.getParam("mass"),
  85220. material: material
  85221. };
  85222. // A simple extend, in case native options were used.
  85223. var nativeOptions = impostor.getParam("nativeOptions");
  85224. for (var key in nativeOptions) {
  85225. if (nativeOptions.hasOwnProperty(key)) {
  85226. bodyCreationObject[key] = nativeOptions[key];
  85227. }
  85228. }
  85229. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85230. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85231. this.world.addEventListener("preStep", impostor.beforeStep);
  85232. this.world.addEventListener("postStep", impostor.afterStep);
  85233. impostor.physicsBody.addShape(shape);
  85234. this.world.add(impostor.physicsBody);
  85235. //try to keep the body moving in the right direction by taking old properties.
  85236. //Should be tested!
  85237. if (oldBody) {
  85238. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85239. impostor.physicsBody[param].copy(oldBody[param]);
  85240. });
  85241. }
  85242. this._processChildMeshes(impostor);
  85243. }
  85244. //now update the body's transformation
  85245. this._updatePhysicsBodyTransformation(impostor);
  85246. };
  85247. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85248. var _this = this;
  85249. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85250. var currentRotation = mainImpostor.object.rotationQuaternion;
  85251. if (meshChildren.length) {
  85252. var processMesh = function (localPosition, mesh) {
  85253. if (!currentRotation || !mesh.rotationQuaternion) {
  85254. return;
  85255. }
  85256. var childImpostor = mesh.getPhysicsImpostor();
  85257. if (childImpostor) {
  85258. var parent = childImpostor.parent;
  85259. if (parent !== mainImpostor) {
  85260. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85261. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85262. if (childImpostor.physicsBody) {
  85263. _this.removePhysicsBody(childImpostor);
  85264. childImpostor.physicsBody = null;
  85265. }
  85266. childImpostor.parent = mainImpostor;
  85267. childImpostor.resetUpdateFlags();
  85268. 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));
  85269. //Add the mass of the children.
  85270. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85271. }
  85272. }
  85273. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85274. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85275. };
  85276. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85277. }
  85278. };
  85279. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85280. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85281. this.world.removeEventListener("preStep", impostor.beforeStep);
  85282. this.world.removeEventListener("postStep", impostor.afterStep);
  85283. this.world.remove(impostor.physicsBody);
  85284. };
  85285. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85286. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85287. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85288. if (!mainBody || !connectedBody) {
  85289. return;
  85290. }
  85291. var constraint;
  85292. var jointData = impostorJoint.joint.jointData;
  85293. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85294. var constraintData = {
  85295. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85296. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85297. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85298. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85299. maxForce: jointData.nativeParams.maxForce,
  85300. collideConnected: !!jointData.collision
  85301. };
  85302. switch (impostorJoint.joint.type) {
  85303. case BABYLON.PhysicsJoint.HingeJoint:
  85304. case BABYLON.PhysicsJoint.Hinge2Joint:
  85305. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85306. break;
  85307. case BABYLON.PhysicsJoint.DistanceJoint:
  85308. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85309. break;
  85310. case BABYLON.PhysicsJoint.SpringJoint:
  85311. var springData = jointData;
  85312. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85313. restLength: springData.length,
  85314. stiffness: springData.stiffness,
  85315. damping: springData.damping,
  85316. localAnchorA: constraintData.pivotA,
  85317. localAnchorB: constraintData.pivotB
  85318. });
  85319. break;
  85320. case BABYLON.PhysicsJoint.LockJoint:
  85321. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85322. break;
  85323. case BABYLON.PhysicsJoint.PointToPointJoint:
  85324. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85325. default:
  85326. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85327. break;
  85328. }
  85329. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85330. constraint.collideConnected = !!jointData.collision;
  85331. impostorJoint.joint.physicsJoint = constraint;
  85332. //don't add spring as constraint, as it is not one.
  85333. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85334. this.world.addConstraint(constraint);
  85335. }
  85336. else {
  85337. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85338. constraint.applyForce();
  85339. });
  85340. }
  85341. };
  85342. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85343. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85344. };
  85345. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85346. var index;
  85347. var mat;
  85348. for (index = 0; index < this._physicsMaterials.length; index++) {
  85349. mat = this._physicsMaterials[index];
  85350. if (mat.friction === friction && mat.restitution === restitution) {
  85351. return mat;
  85352. }
  85353. }
  85354. var currentMat = new this.BJSCANNON.Material(name);
  85355. currentMat.friction = friction;
  85356. currentMat.restitution = restitution;
  85357. this._physicsMaterials.push(currentMat);
  85358. return currentMat;
  85359. };
  85360. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85361. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85362. };
  85363. CannonJSPlugin.prototype._createShape = function (impostor) {
  85364. var object = impostor.object;
  85365. var returnValue;
  85366. var extendSize = impostor.getObjectExtendSize();
  85367. switch (impostor.type) {
  85368. case BABYLON.PhysicsImpostor.SphereImpostor:
  85369. var radiusX = extendSize.x;
  85370. var radiusY = extendSize.y;
  85371. var radiusZ = extendSize.z;
  85372. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85373. break;
  85374. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85375. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85376. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85377. break;
  85378. case BABYLON.PhysicsImpostor.BoxImpostor:
  85379. var box = extendSize.scale(0.5);
  85380. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85381. break;
  85382. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85383. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85384. returnValue = new this.BJSCANNON.Plane();
  85385. break;
  85386. case BABYLON.PhysicsImpostor.MeshImpostor:
  85387. // should transform the vertex data to world coordinates!!
  85388. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85389. var rawFaces = object.getIndices ? object.getIndices() : [];
  85390. if (!rawVerts)
  85391. return;
  85392. // get only scale! so the object could transform correctly.
  85393. var oldPosition = object.position.clone();
  85394. var oldRotation = object.rotation && object.rotation.clone();
  85395. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85396. object.position.copyFromFloats(0, 0, 0);
  85397. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85398. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85399. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85400. var transform = object.computeWorldMatrix(true);
  85401. // convert rawVerts to object space
  85402. var temp = new Array();
  85403. var index;
  85404. for (index = 0; index < rawVerts.length; index += 3) {
  85405. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85406. }
  85407. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85408. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85409. //now set back the transformation!
  85410. object.position.copyFrom(oldPosition);
  85411. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85412. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85413. break;
  85414. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85415. var oldPosition2 = object.position.clone();
  85416. var oldRotation2 = object.rotation && object.rotation.clone();
  85417. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85418. object.position.copyFromFloats(0, 0, 0);
  85419. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85420. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85421. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85422. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85423. returnValue = this._createHeightmap(object);
  85424. object.position.copyFrom(oldPosition2);
  85425. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85426. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85427. object.computeWorldMatrix(true);
  85428. break;
  85429. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85430. returnValue = new this.BJSCANNON.Particle();
  85431. break;
  85432. }
  85433. return returnValue;
  85434. };
  85435. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85436. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85437. var transform = object.computeWorldMatrix(true);
  85438. // convert rawVerts to object space
  85439. var temp = new Array();
  85440. var index;
  85441. for (index = 0; index < pos.length; index += 3) {
  85442. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85443. }
  85444. pos = temp;
  85445. var matrix = new Array();
  85446. //For now pointDepth will not be used and will be automatically calculated.
  85447. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85448. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85449. var boundingInfo = object.getBoundingInfo();
  85450. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85451. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85452. var elementSize = dim * 2 / arraySize;
  85453. for (var i = 0; i < pos.length; i = i + 3) {
  85454. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85455. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85456. var y = -pos[i + 2] + minY;
  85457. if (!matrix[x]) {
  85458. matrix[x] = [];
  85459. }
  85460. if (!matrix[x][z]) {
  85461. matrix[x][z] = y;
  85462. }
  85463. matrix[x][z] = Math.max(y, matrix[x][z]);
  85464. }
  85465. for (var x = 0; x <= arraySize; ++x) {
  85466. if (!matrix[x]) {
  85467. var loc = 1;
  85468. while (!matrix[(x + loc) % arraySize]) {
  85469. loc++;
  85470. }
  85471. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85472. //console.log("missing x", x);
  85473. }
  85474. for (var z = 0; z <= arraySize; ++z) {
  85475. if (!matrix[x][z]) {
  85476. var loc = 1;
  85477. var newValue;
  85478. while (newValue === undefined) {
  85479. newValue = matrix[x][(z + loc++) % arraySize];
  85480. }
  85481. matrix[x][z] = newValue;
  85482. }
  85483. }
  85484. }
  85485. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85486. elementSize: elementSize
  85487. });
  85488. //For future reference, needed for body transformation
  85489. shape.minY = minY;
  85490. return shape;
  85491. };
  85492. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85493. var object = impostor.object;
  85494. //make sure it is updated...
  85495. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85496. // The delta between the mesh position and the mesh bounding box center
  85497. var bInfo = object.getBoundingInfo();
  85498. if (!bInfo)
  85499. return;
  85500. var center = impostor.getObjectCenter();
  85501. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85502. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85503. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85504. this._tmpPosition.copyFrom(center);
  85505. var quaternion = object.rotationQuaternion;
  85506. if (!quaternion) {
  85507. return;
  85508. }
  85509. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85510. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85511. //-90 DEG in X, precalculated
  85512. quaternion = quaternion.multiply(this._minus90X);
  85513. //Invert! (Precalculated, 90 deg in X)
  85514. //No need to clone. this will never change.
  85515. impostor.setDeltaRotation(this._plus90X);
  85516. }
  85517. //If it is a heightfield, if should be centered.
  85518. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85519. var mesh = object;
  85520. var boundingInfo = mesh.getBoundingInfo();
  85521. //calculate the correct body position:
  85522. var rotationQuaternion = mesh.rotationQuaternion;
  85523. mesh.rotationQuaternion = this._tmpUnityRotation;
  85524. mesh.computeWorldMatrix(true);
  85525. //get original center with no rotation
  85526. var c = center.clone();
  85527. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85528. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85529. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85530. mesh.setPreTransformMatrix(p);
  85531. mesh.computeWorldMatrix(true);
  85532. //calculate the translation
  85533. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85534. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85535. //add it inverted to the delta
  85536. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85537. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85538. //rotation is back
  85539. mesh.rotationQuaternion = rotationQuaternion;
  85540. mesh.setPreTransformMatrix(oldPivot);
  85541. mesh.computeWorldMatrix(true);
  85542. }
  85543. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85544. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85545. //this._tmpPosition.copyFrom(object.position);
  85546. }
  85547. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85548. //Now update the impostor object
  85549. impostor.physicsBody.position.copy(this._tmpPosition);
  85550. impostor.physicsBody.quaternion.copy(quaternion);
  85551. };
  85552. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85553. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85554. if (impostor.object.rotationQuaternion) {
  85555. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85556. }
  85557. };
  85558. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85559. impostor.physicsBody.position.copy(newPosition);
  85560. impostor.physicsBody.quaternion.copy(newRotation);
  85561. };
  85562. CannonJSPlugin.prototype.isSupported = function () {
  85563. return this.BJSCANNON !== undefined;
  85564. };
  85565. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85566. impostor.physicsBody.velocity.copy(velocity);
  85567. };
  85568. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85569. impostor.physicsBody.angularVelocity.copy(velocity);
  85570. };
  85571. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85572. var v = impostor.physicsBody.velocity;
  85573. if (!v) {
  85574. return null;
  85575. }
  85576. return new BABYLON.Vector3(v.x, v.y, v.z);
  85577. };
  85578. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85579. var v = impostor.physicsBody.angularVelocity;
  85580. if (!v) {
  85581. return null;
  85582. }
  85583. return new BABYLON.Vector3(v.x, v.y, v.z);
  85584. };
  85585. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85586. impostor.physicsBody.mass = mass;
  85587. impostor.physicsBody.updateMassProperties();
  85588. };
  85589. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85590. return impostor.physicsBody.mass;
  85591. };
  85592. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85593. return impostor.physicsBody.material.friction;
  85594. };
  85595. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85596. impostor.physicsBody.material.friction = friction;
  85597. };
  85598. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85599. return impostor.physicsBody.material.restitution;
  85600. };
  85601. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85602. impostor.physicsBody.material.restitution = restitution;
  85603. };
  85604. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85605. impostor.physicsBody.sleep();
  85606. };
  85607. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85608. impostor.physicsBody.wakeUp();
  85609. };
  85610. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85611. joint.physicsJoint.distance = maxDistance;
  85612. };
  85613. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85614. // if (!motorIndex) {
  85615. // joint.physicsJoint.enableMotor();
  85616. // }
  85617. // }
  85618. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85619. // if (!motorIndex) {
  85620. // joint.physicsJoint.disableMotor();
  85621. // }
  85622. // }
  85623. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85624. if (!motorIndex) {
  85625. joint.physicsJoint.enableMotor();
  85626. joint.physicsJoint.setMotorSpeed(speed);
  85627. if (maxForce) {
  85628. this.setLimit(joint, maxForce);
  85629. }
  85630. }
  85631. };
  85632. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85633. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85634. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85635. };
  85636. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85637. var body = impostor.physicsBody;
  85638. mesh.position.x = body.position.x;
  85639. mesh.position.y = body.position.y;
  85640. mesh.position.z = body.position.z;
  85641. if (mesh.rotationQuaternion) {
  85642. mesh.rotationQuaternion.x = body.quaternion.x;
  85643. mesh.rotationQuaternion.y = body.quaternion.y;
  85644. mesh.rotationQuaternion.z = body.quaternion.z;
  85645. mesh.rotationQuaternion.w = body.quaternion.w;
  85646. }
  85647. };
  85648. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85649. var shape = impostor.physicsBody.shapes[0];
  85650. return shape.boundingSphereRadius;
  85651. };
  85652. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85653. var shape = impostor.physicsBody.shapes[0];
  85654. result.x = shape.halfExtents.x * 2;
  85655. result.y = shape.halfExtents.y * 2;
  85656. result.z = shape.halfExtents.z * 2;
  85657. };
  85658. CannonJSPlugin.prototype.dispose = function () {
  85659. };
  85660. CannonJSPlugin.prototype._extendNamespace = function () {
  85661. //this will force cannon to execute at least one step when using interpolation
  85662. var step_tmp1 = new this.BJSCANNON.Vec3();
  85663. var Engine = this.BJSCANNON;
  85664. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85665. maxSubSteps = maxSubSteps || 10;
  85666. timeSinceLastCalled = timeSinceLastCalled || 0;
  85667. if (timeSinceLastCalled === 0) {
  85668. this.internalStep(dt);
  85669. this.time += dt;
  85670. }
  85671. else {
  85672. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85673. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85674. var t0 = performance.now();
  85675. for (var i = 0; i !== internalSteps; i++) {
  85676. this.internalStep(dt);
  85677. if (performance.now() - t0 > dt * 1000) {
  85678. break;
  85679. }
  85680. }
  85681. this.time += timeSinceLastCalled;
  85682. var h = this.time % dt;
  85683. var h_div_dt = h / dt;
  85684. var interpvelo = step_tmp1;
  85685. var bodies = this.bodies;
  85686. for (var j = 0; j !== bodies.length; j++) {
  85687. var b = bodies[j];
  85688. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  85689. b.position.vsub(b.previousPosition, interpvelo);
  85690. interpvelo.scale(h_div_dt, interpvelo);
  85691. b.position.vadd(interpvelo, b.interpolatedPosition);
  85692. }
  85693. else {
  85694. b.interpolatedPosition.copy(b.position);
  85695. b.interpolatedQuaternion.copy(b.quaternion);
  85696. }
  85697. }
  85698. }
  85699. };
  85700. };
  85701. return CannonJSPlugin;
  85702. }());
  85703. BABYLON.CannonJSPlugin = CannonJSPlugin;
  85704. })(BABYLON || (BABYLON = {}));
  85705. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  85706. var BABYLON;
  85707. (function (BABYLON) {
  85708. var OimoJSPlugin = /** @class */ (function () {
  85709. function OimoJSPlugin(iterations) {
  85710. this.name = "OimoJSPlugin";
  85711. this._tmpImpostorsArray = [];
  85712. this._tmpPositionVector = BABYLON.Vector3.Zero();
  85713. this.BJSOIMO = OIMO;
  85714. this.world = new this.BJSOIMO.World({
  85715. iterations: iterations
  85716. });
  85717. this.world.clear();
  85718. }
  85719. OimoJSPlugin.prototype.setGravity = function (gravity) {
  85720. this.world.gravity.copy(gravity);
  85721. };
  85722. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  85723. this.world.timeStep = timeStep;
  85724. };
  85725. OimoJSPlugin.prototype.getTimeStep = function () {
  85726. return this.world.timeStep;
  85727. };
  85728. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  85729. var _this = this;
  85730. impostors.forEach(function (impostor) {
  85731. impostor.beforeStep();
  85732. });
  85733. this.world.step();
  85734. impostors.forEach(function (impostor) {
  85735. impostor.afterStep();
  85736. //update the ordered impostors array
  85737. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  85738. });
  85739. //check for collisions
  85740. var contact = this.world.contacts;
  85741. while (contact !== null) {
  85742. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  85743. contact = contact.next;
  85744. continue;
  85745. }
  85746. //is this body colliding with any other? get the impostor
  85747. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  85748. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  85749. if (!mainImpostor || !collidingImpostor) {
  85750. contact = contact.next;
  85751. continue;
  85752. }
  85753. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  85754. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  85755. contact = contact.next;
  85756. }
  85757. };
  85758. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85759. var mass = impostor.physicsBody.mass;
  85760. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  85761. };
  85762. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85763. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  85764. this.applyImpulse(impostor, force, contactPoint);
  85765. };
  85766. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85767. var _this = this;
  85768. //parent-child relationship. Does this impostor has a parent impostor?
  85769. if (impostor.parent) {
  85770. if (impostor.physicsBody) {
  85771. this.removePhysicsBody(impostor);
  85772. //TODO is that needed?
  85773. impostor.forceUpdate();
  85774. }
  85775. return;
  85776. }
  85777. if (impostor.isBodyInitRequired()) {
  85778. var bodyConfig = {
  85779. name: impostor.uniqueId,
  85780. //Oimo must have mass, also for static objects.
  85781. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  85782. size: [],
  85783. type: [],
  85784. pos: [],
  85785. posShape: [],
  85786. rot: [],
  85787. rotShape: [],
  85788. move: impostor.getParam("mass") !== 0,
  85789. density: impostor.getParam("mass"),
  85790. friction: impostor.getParam("friction"),
  85791. restitution: impostor.getParam("restitution"),
  85792. //Supporting older versions of Oimo
  85793. world: this.world
  85794. };
  85795. var impostors = [impostor];
  85796. var addToArray = function (parent) {
  85797. if (!parent.getChildMeshes)
  85798. return;
  85799. parent.getChildMeshes().forEach(function (m) {
  85800. if (m.physicsImpostor) {
  85801. impostors.push(m.physicsImpostor);
  85802. //m.physicsImpostor._init();
  85803. }
  85804. });
  85805. };
  85806. addToArray(impostor.object);
  85807. var checkWithEpsilon_1 = function (value) {
  85808. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  85809. };
  85810. impostors.forEach(function (i) {
  85811. if (!i.object.rotationQuaternion) {
  85812. return;
  85813. }
  85814. //get the correct bounding box
  85815. var oldQuaternion = i.object.rotationQuaternion;
  85816. var rot = oldQuaternion.toEulerAngles();
  85817. var extendSize = i.getObjectExtendSize();
  85818. var radToDeg = 57.295779513082320876;
  85819. if (i === impostor) {
  85820. var center = impostor.getObjectCenter();
  85821. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  85822. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  85823. //Can also use Array.prototype.push.apply
  85824. bodyConfig.pos.push(center.x);
  85825. bodyConfig.pos.push(center.y);
  85826. bodyConfig.pos.push(center.z);
  85827. bodyConfig.posShape.push(0, 0, 0);
  85828. //tmp solution
  85829. bodyConfig.rot.push(rot.x * radToDeg);
  85830. bodyConfig.rot.push(rot.y * radToDeg);
  85831. bodyConfig.rot.push(rot.z * radToDeg);
  85832. bodyConfig.rotShape.push(0, 0, 0);
  85833. }
  85834. else {
  85835. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  85836. bodyConfig.posShape.push(localPosition.x);
  85837. bodyConfig.posShape.push(localPosition.y);
  85838. bodyConfig.posShape.push(localPosition.z);
  85839. bodyConfig.pos.push(0, 0, 0);
  85840. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  85841. bodyConfig.rot.push(0);
  85842. bodyConfig.rot.push(0);
  85843. bodyConfig.rot.push(0);
  85844. bodyConfig.rotShape.push(rot.x * radToDeg);
  85845. bodyConfig.rotShape.push(rot.y * radToDeg);
  85846. bodyConfig.rotShape.push(rot.z * radToDeg);
  85847. }
  85848. // register mesh
  85849. switch (i.type) {
  85850. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85851. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  85852. case BABYLON.PhysicsImpostor.SphereImpostor:
  85853. var radiusX = extendSize.x;
  85854. var radiusY = extendSize.y;
  85855. var radiusZ = extendSize.z;
  85856. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  85857. bodyConfig.type.push('sphere');
  85858. //due to the way oimo works with compounds, add 3 times
  85859. bodyConfig.size.push(size);
  85860. bodyConfig.size.push(size);
  85861. bodyConfig.size.push(size);
  85862. break;
  85863. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85864. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  85865. var sizeY = checkWithEpsilon_1(extendSize.y);
  85866. bodyConfig.type.push('cylinder');
  85867. bodyConfig.size.push(sizeX);
  85868. bodyConfig.size.push(sizeY);
  85869. //due to the way oimo works with compounds, add one more value.
  85870. bodyConfig.size.push(sizeY);
  85871. break;
  85872. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85873. case BABYLON.PhysicsImpostor.BoxImpostor:
  85874. default:
  85875. var sizeX = checkWithEpsilon_1(extendSize.x);
  85876. var sizeY = checkWithEpsilon_1(extendSize.y);
  85877. var sizeZ = checkWithEpsilon_1(extendSize.z);
  85878. bodyConfig.type.push('box');
  85879. //if (i === impostor) {
  85880. bodyConfig.size.push(sizeX);
  85881. bodyConfig.size.push(sizeY);
  85882. bodyConfig.size.push(sizeZ);
  85883. //} else {
  85884. // bodyConfig.size.push(0,0,0);
  85885. //}
  85886. break;
  85887. }
  85888. //actually not needed, but hey...
  85889. i.object.rotationQuaternion = oldQuaternion;
  85890. });
  85891. impostor.physicsBody = this.world.add(bodyConfig);
  85892. }
  85893. else {
  85894. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  85895. }
  85896. impostor.setDeltaPosition(this._tmpPositionVector);
  85897. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  85898. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  85899. };
  85900. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85901. //impostor.physicsBody.dispose();
  85902. //Same as : (older oimo versions)
  85903. this.world.removeRigidBody(impostor.physicsBody);
  85904. };
  85905. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85906. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85907. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85908. if (!mainBody || !connectedBody) {
  85909. return;
  85910. }
  85911. var jointData = impostorJoint.joint.jointData;
  85912. var options = jointData.nativeParams || {};
  85913. var type;
  85914. var nativeJointData = {
  85915. body1: mainBody,
  85916. body2: connectedBody,
  85917. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  85918. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  85919. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  85920. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  85921. min: options.min,
  85922. max: options.max,
  85923. collision: options.collision || jointData.collision,
  85924. spring: options.spring,
  85925. //supporting older version of Oimo
  85926. world: this.world
  85927. };
  85928. switch (impostorJoint.joint.type) {
  85929. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85930. type = "jointBall";
  85931. break;
  85932. case BABYLON.PhysicsJoint.SpringJoint:
  85933. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  85934. var springData = jointData;
  85935. nativeJointData.min = springData.length || nativeJointData.min;
  85936. //Max should also be set, just make sure it is at least min
  85937. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  85938. case BABYLON.PhysicsJoint.DistanceJoint:
  85939. type = "jointDistance";
  85940. nativeJointData.max = jointData.maxDistance;
  85941. break;
  85942. case BABYLON.PhysicsJoint.PrismaticJoint:
  85943. type = "jointPrisme";
  85944. break;
  85945. case BABYLON.PhysicsJoint.SliderJoint:
  85946. type = "jointSlide";
  85947. break;
  85948. case BABYLON.PhysicsJoint.WheelJoint:
  85949. type = "jointWheel";
  85950. break;
  85951. case BABYLON.PhysicsJoint.HingeJoint:
  85952. default:
  85953. type = "jointHinge";
  85954. break;
  85955. }
  85956. nativeJointData.type = type;
  85957. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  85958. };
  85959. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85960. //Bug in Oimo prevents us from disposing a joint in the playground
  85961. //joint.joint.physicsJoint.dispose();
  85962. //So we will bruteforce it!
  85963. try {
  85964. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  85965. }
  85966. catch (e) {
  85967. BABYLON.Tools.Warn(e);
  85968. }
  85969. };
  85970. OimoJSPlugin.prototype.isSupported = function () {
  85971. return this.BJSOIMO !== undefined;
  85972. };
  85973. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85974. if (!impostor.physicsBody.sleeping) {
  85975. //TODO check that
  85976. /*if (impostor.physicsBody.shapes.next) {
  85977. var parentShape = this._getLastShape(impostor.physicsBody);
  85978. impostor.object.position.copyFrom(parentShape.position);
  85979. console.log(parentShape.position);
  85980. } else {*/
  85981. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  85982. //}
  85983. if (impostor.object.rotationQuaternion) {
  85984. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  85985. }
  85986. }
  85987. };
  85988. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85989. var body = impostor.physicsBody;
  85990. body.position.copy(newPosition);
  85991. body.orientation.copy(newRotation);
  85992. body.syncShapes();
  85993. body.awake();
  85994. };
  85995. /*private _getLastShape(body: any): any {
  85996. var lastShape = body.shapes;
  85997. while (lastShape.next) {
  85998. lastShape = lastShape.next;
  85999. }
  86000. return lastShape;
  86001. }*/
  86002. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86003. impostor.physicsBody.linearVelocity.copy(velocity);
  86004. };
  86005. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86006. impostor.physicsBody.angularVelocity.copy(velocity);
  86007. };
  86008. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86009. var v = impostor.physicsBody.linearVelocity;
  86010. if (!v) {
  86011. return null;
  86012. }
  86013. return new BABYLON.Vector3(v.x, v.y, v.z);
  86014. };
  86015. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86016. var v = impostor.physicsBody.angularVelocity;
  86017. if (!v) {
  86018. return null;
  86019. }
  86020. return new BABYLON.Vector3(v.x, v.y, v.z);
  86021. };
  86022. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86023. var staticBody = mass === 0;
  86024. //this will actually set the body's density and not its mass.
  86025. //But this is how oimo treats the mass variable.
  86026. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86027. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86028. };
  86029. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86030. return impostor.physicsBody.shapes.density;
  86031. };
  86032. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86033. return impostor.physicsBody.shapes.friction;
  86034. };
  86035. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86036. impostor.physicsBody.shapes.friction = friction;
  86037. };
  86038. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86039. return impostor.physicsBody.shapes.restitution;
  86040. };
  86041. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86042. impostor.physicsBody.shapes.restitution = restitution;
  86043. };
  86044. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86045. impostor.physicsBody.sleep();
  86046. };
  86047. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86048. impostor.physicsBody.awake();
  86049. };
  86050. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86051. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86052. if (minDistance !== void 0) {
  86053. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86054. }
  86055. };
  86056. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86057. //TODO separate rotational and transational motors.
  86058. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86059. if (motor) {
  86060. motor.setMotor(speed, maxForce);
  86061. }
  86062. };
  86063. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86064. //TODO separate rotational and transational motors.
  86065. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86066. if (motor) {
  86067. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86068. }
  86069. };
  86070. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86071. var body = impostor.physicsBody;
  86072. mesh.position.x = body.position.x;
  86073. mesh.position.y = body.position.y;
  86074. mesh.position.z = body.position.z;
  86075. if (mesh.rotationQuaternion) {
  86076. mesh.rotationQuaternion.x = body.orientation.x;
  86077. mesh.rotationQuaternion.y = body.orientation.y;
  86078. mesh.rotationQuaternion.z = body.orientation.z;
  86079. mesh.rotationQuaternion.w = body.orientation.s;
  86080. }
  86081. };
  86082. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86083. return impostor.physicsBody.shapes.radius;
  86084. };
  86085. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86086. var shape = impostor.physicsBody.shapes;
  86087. result.x = shape.halfWidth * 2;
  86088. result.y = shape.halfHeight * 2;
  86089. result.z = shape.halfDepth * 2;
  86090. };
  86091. OimoJSPlugin.prototype.dispose = function () {
  86092. this.world.clear();
  86093. };
  86094. return OimoJSPlugin;
  86095. }());
  86096. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86097. })(BABYLON || (BABYLON = {}));
  86098. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86099. var BABYLON;
  86100. (function (BABYLON) {
  86101. /*
  86102. * Based on jsTGALoader - Javascript loader for TGA file
  86103. * By Vincent Thibault
  86104. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86105. */
  86106. var TGATools = /** @class */ (function () {
  86107. function TGATools() {
  86108. }
  86109. TGATools.GetTGAHeader = function (data) {
  86110. var offset = 0;
  86111. var header = {
  86112. id_length: data[offset++],
  86113. colormap_type: data[offset++],
  86114. image_type: data[offset++],
  86115. colormap_index: data[offset++] | data[offset++] << 8,
  86116. colormap_length: data[offset++] | data[offset++] << 8,
  86117. colormap_size: data[offset++],
  86118. origin: [
  86119. data[offset++] | data[offset++] << 8,
  86120. data[offset++] | data[offset++] << 8
  86121. ],
  86122. width: data[offset++] | data[offset++] << 8,
  86123. height: data[offset++] | data[offset++] << 8,
  86124. pixel_size: data[offset++],
  86125. flags: data[offset++]
  86126. };
  86127. return header;
  86128. };
  86129. TGATools.UploadContent = function (gl, data) {
  86130. // Not enough data to contain header ?
  86131. if (data.length < 19) {
  86132. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86133. return;
  86134. }
  86135. // Read Header
  86136. var offset = 18;
  86137. var header = TGATools.GetTGAHeader(data);
  86138. // Assume it's a valid Targa file.
  86139. if (header.id_length + offset > data.length) {
  86140. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86141. return;
  86142. }
  86143. // Skip not needed data
  86144. offset += header.id_length;
  86145. var use_rle = false;
  86146. var use_pal = false;
  86147. var use_grey = false;
  86148. // Get some informations.
  86149. switch (header.image_type) {
  86150. case TGATools._TYPE_RLE_INDEXED:
  86151. use_rle = true;
  86152. case TGATools._TYPE_INDEXED:
  86153. use_pal = true;
  86154. break;
  86155. case TGATools._TYPE_RLE_RGB:
  86156. use_rle = true;
  86157. case TGATools._TYPE_RGB:
  86158. // use_rgb = true;
  86159. break;
  86160. case TGATools._TYPE_RLE_GREY:
  86161. use_rle = true;
  86162. case TGATools._TYPE_GREY:
  86163. use_grey = true;
  86164. break;
  86165. }
  86166. var pixel_data;
  86167. // var numAlphaBits = header.flags & 0xf;
  86168. var pixel_size = header.pixel_size >> 3;
  86169. var pixel_total = header.width * header.height * pixel_size;
  86170. // Read palettes
  86171. var palettes;
  86172. if (use_pal) {
  86173. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86174. }
  86175. // Read LRE
  86176. if (use_rle) {
  86177. pixel_data = new Uint8Array(pixel_total);
  86178. var c, count, i;
  86179. var localOffset = 0;
  86180. var pixels = new Uint8Array(pixel_size);
  86181. while (offset < pixel_total && localOffset < pixel_total) {
  86182. c = data[offset++];
  86183. count = (c & 0x7f) + 1;
  86184. // RLE pixels
  86185. if (c & 0x80) {
  86186. // Bind pixel tmp array
  86187. for (i = 0; i < pixel_size; ++i) {
  86188. pixels[i] = data[offset++];
  86189. }
  86190. // Copy pixel array
  86191. for (i = 0; i < count; ++i) {
  86192. pixel_data.set(pixels, localOffset + i * pixel_size);
  86193. }
  86194. localOffset += pixel_size * count;
  86195. }
  86196. // Raw pixels
  86197. else {
  86198. count *= pixel_size;
  86199. for (i = 0; i < count; ++i) {
  86200. pixel_data[localOffset + i] = data[offset++];
  86201. }
  86202. localOffset += count;
  86203. }
  86204. }
  86205. }
  86206. // RAW Pixels
  86207. else {
  86208. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86209. }
  86210. // Load to texture
  86211. var x_start, y_start, x_step, y_step, y_end, x_end;
  86212. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86213. default:
  86214. case TGATools._ORIGIN_UL:
  86215. x_start = 0;
  86216. x_step = 1;
  86217. x_end = header.width;
  86218. y_start = 0;
  86219. y_step = 1;
  86220. y_end = header.height;
  86221. break;
  86222. case TGATools._ORIGIN_BL:
  86223. x_start = 0;
  86224. x_step = 1;
  86225. x_end = header.width;
  86226. y_start = header.height - 1;
  86227. y_step = -1;
  86228. y_end = -1;
  86229. break;
  86230. case TGATools._ORIGIN_UR:
  86231. x_start = header.width - 1;
  86232. x_step = -1;
  86233. x_end = -1;
  86234. y_start = 0;
  86235. y_step = 1;
  86236. y_end = header.height;
  86237. break;
  86238. case TGATools._ORIGIN_BR:
  86239. x_start = header.width - 1;
  86240. x_step = -1;
  86241. x_end = -1;
  86242. y_start = header.height - 1;
  86243. y_step = -1;
  86244. y_end = -1;
  86245. break;
  86246. }
  86247. // Load the specify method
  86248. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86249. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86250. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86251. };
  86252. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86253. var image = pixel_data, colormap = palettes;
  86254. var width = header.width, height = header.height;
  86255. var color, i = 0, x, y;
  86256. var imageData = new Uint8Array(width * height * 4);
  86257. for (y = y_start; y !== y_end; y += y_step) {
  86258. for (x = x_start; x !== x_end; x += x_step, i++) {
  86259. color = image[i];
  86260. imageData[(x + width * y) * 4 + 3] = 255;
  86261. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86262. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86263. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86264. }
  86265. }
  86266. return imageData;
  86267. };
  86268. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86269. var image = pixel_data;
  86270. var width = header.width, height = header.height;
  86271. var color, i = 0, x, y;
  86272. var imageData = new Uint8Array(width * height * 4);
  86273. for (y = y_start; y !== y_end; y += y_step) {
  86274. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86275. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86276. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86277. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86278. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86279. imageData[(x + width * y) * 4 + 0] = r;
  86280. imageData[(x + width * y) * 4 + 1] = g;
  86281. imageData[(x + width * y) * 4 + 2] = b;
  86282. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86283. }
  86284. }
  86285. return imageData;
  86286. };
  86287. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86288. var image = pixel_data;
  86289. var width = header.width, height = header.height;
  86290. var i = 0, x, y;
  86291. var imageData = new Uint8Array(width * height * 4);
  86292. for (y = y_start; y !== y_end; y += y_step) {
  86293. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86294. imageData[(x + width * y) * 4 + 3] = 255;
  86295. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86296. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86297. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86298. }
  86299. }
  86300. return imageData;
  86301. };
  86302. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86303. var image = pixel_data;
  86304. var width = header.width, height = header.height;
  86305. var i = 0, x, y;
  86306. var imageData = new Uint8Array(width * height * 4);
  86307. for (y = y_start; y !== y_end; y += y_step) {
  86308. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86309. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86310. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86311. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86312. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86313. }
  86314. }
  86315. return imageData;
  86316. };
  86317. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86318. var image = pixel_data;
  86319. var width = header.width, height = header.height;
  86320. var color, i = 0, x, y;
  86321. var imageData = new Uint8Array(width * height * 4);
  86322. for (y = y_start; y !== y_end; y += y_step) {
  86323. for (x = x_start; x !== x_end; x += x_step, i++) {
  86324. color = image[i];
  86325. imageData[(x + width * y) * 4 + 0] = color;
  86326. imageData[(x + width * y) * 4 + 1] = color;
  86327. imageData[(x + width * y) * 4 + 2] = color;
  86328. imageData[(x + width * y) * 4 + 3] = 255;
  86329. }
  86330. }
  86331. return imageData;
  86332. };
  86333. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86334. var image = pixel_data;
  86335. var width = header.width, height = header.height;
  86336. var i = 0, x, y;
  86337. var imageData = new Uint8Array(width * height * 4);
  86338. for (y = y_start; y !== y_end; y += y_step) {
  86339. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86340. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86341. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86342. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86343. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86344. }
  86345. }
  86346. return imageData;
  86347. };
  86348. //private static _TYPE_NO_DATA = 0;
  86349. TGATools._TYPE_INDEXED = 1;
  86350. TGATools._TYPE_RGB = 2;
  86351. TGATools._TYPE_GREY = 3;
  86352. TGATools._TYPE_RLE_INDEXED = 9;
  86353. TGATools._TYPE_RLE_RGB = 10;
  86354. TGATools._TYPE_RLE_GREY = 11;
  86355. TGATools._ORIGIN_MASK = 0x30;
  86356. TGATools._ORIGIN_SHIFT = 0x04;
  86357. TGATools._ORIGIN_BL = 0x00;
  86358. TGATools._ORIGIN_BR = 0x01;
  86359. TGATools._ORIGIN_UL = 0x02;
  86360. TGATools._ORIGIN_UR = 0x03;
  86361. return TGATools;
  86362. }());
  86363. BABYLON.TGATools = TGATools;
  86364. })(BABYLON || (BABYLON = {}));
  86365. //# sourceMappingURL=babylon.tga.js.map
  86366. var BABYLON;
  86367. (function (BABYLON) {
  86368. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86369. // All values and structures referenced from:
  86370. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86371. var DDS_MAGIC = 0x20534444;
  86372. var
  86373. //DDSD_CAPS = 0x1,
  86374. //DDSD_HEIGHT = 0x2,
  86375. //DDSD_WIDTH = 0x4,
  86376. //DDSD_PITCH = 0x8,
  86377. //DDSD_PIXELFORMAT = 0x1000,
  86378. DDSD_MIPMAPCOUNT = 0x20000;
  86379. //DDSD_LINEARSIZE = 0x80000,
  86380. //DDSD_DEPTH = 0x800000;
  86381. // var DDSCAPS_COMPLEX = 0x8,
  86382. // DDSCAPS_MIPMAP = 0x400000,
  86383. // DDSCAPS_TEXTURE = 0x1000;
  86384. var DDSCAPS2_CUBEMAP = 0x200;
  86385. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86386. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86387. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86388. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86389. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86390. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86391. // DDSCAPS2_VOLUME = 0x200000;
  86392. var
  86393. //DDPF_ALPHAPIXELS = 0x1,
  86394. //DDPF_ALPHA = 0x2,
  86395. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86396. //DDPF_YUV = 0x200,
  86397. DDPF_LUMINANCE = 0x20000;
  86398. function FourCCToInt32(value) {
  86399. return value.charCodeAt(0) +
  86400. (value.charCodeAt(1) << 8) +
  86401. (value.charCodeAt(2) << 16) +
  86402. (value.charCodeAt(3) << 24);
  86403. }
  86404. function Int32ToFourCC(value) {
  86405. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86406. }
  86407. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86408. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86409. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86410. var FOURCC_DX10 = FourCCToInt32("DX10");
  86411. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86412. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86413. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86414. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86415. var headerLengthInt = 31; // The header length in 32 bit ints
  86416. // Offsets into the header array
  86417. var off_magic = 0;
  86418. var off_size = 1;
  86419. var off_flags = 2;
  86420. var off_height = 3;
  86421. var off_width = 4;
  86422. var off_mipmapCount = 7;
  86423. var off_pfFlags = 20;
  86424. var off_pfFourCC = 21;
  86425. var off_RGBbpp = 22;
  86426. var off_RMask = 23;
  86427. var off_GMask = 24;
  86428. var off_BMask = 25;
  86429. var off_AMask = 26;
  86430. // var off_caps1 = 27;
  86431. var off_caps2 = 28;
  86432. // var off_caps3 = 29;
  86433. // var off_caps4 = 30;
  86434. var off_dxgiFormat = 32;
  86435. ;
  86436. var DDSTools = /** @class */ (function () {
  86437. function DDSTools() {
  86438. }
  86439. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86440. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86441. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86442. var mipmapCount = 1;
  86443. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86444. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86445. }
  86446. var fourCC = header[off_pfFourCC];
  86447. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86448. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86449. switch (fourCC) {
  86450. case FOURCC_D3DFMT_R16G16B16A16F:
  86451. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86452. break;
  86453. case FOURCC_D3DFMT_R32G32B32A32F:
  86454. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86455. break;
  86456. case FOURCC_DX10:
  86457. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86458. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86459. break;
  86460. }
  86461. }
  86462. return {
  86463. width: header[off_width],
  86464. height: header[off_height],
  86465. mipmapCount: mipmapCount,
  86466. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86467. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86468. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86469. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86470. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86471. dxgiFormat: dxgiFormat,
  86472. textureType: textureType
  86473. };
  86474. };
  86475. DDSTools._ToHalfFloat = function (value) {
  86476. if (!DDSTools._FloatView) {
  86477. DDSTools._FloatView = new Float32Array(1);
  86478. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86479. }
  86480. DDSTools._FloatView[0] = value;
  86481. var x = DDSTools._Int32View[0];
  86482. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86483. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86484. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86485. /* If zero, or denormal, or exponent underflows too much for a denormal
  86486. * half, return signed zero. */
  86487. if (e < 103) {
  86488. return bits;
  86489. }
  86490. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86491. if (e > 142) {
  86492. bits |= 0x7c00;
  86493. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86494. * not Inf, so make sure we set one mantissa bit too. */
  86495. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86496. return bits;
  86497. }
  86498. /* If exponent underflows but not too much, return a denormal */
  86499. if (e < 113) {
  86500. m |= 0x0800;
  86501. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86502. * to 1, which is OK. */
  86503. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86504. return bits;
  86505. }
  86506. bits |= ((e - 112) << 10) | (m >> 1);
  86507. bits += m & 1;
  86508. return bits;
  86509. };
  86510. DDSTools._FromHalfFloat = function (value) {
  86511. var s = (value & 0x8000) >> 15;
  86512. var e = (value & 0x7C00) >> 10;
  86513. var f = value & 0x03FF;
  86514. if (e === 0) {
  86515. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86516. }
  86517. else if (e == 0x1F) {
  86518. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86519. }
  86520. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86521. };
  86522. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86523. var destArray = new Float32Array(dataLength);
  86524. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86525. var index = 0;
  86526. for (var y = 0; y < height; y++) {
  86527. for (var x = 0; x < width; x++) {
  86528. var srcPos = (x + y * width) * 4;
  86529. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86530. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86531. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86532. if (DDSTools.StoreLODInAlphaChannel) {
  86533. destArray[index + 3] = lod;
  86534. }
  86535. else {
  86536. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86537. }
  86538. index += 4;
  86539. }
  86540. }
  86541. return destArray;
  86542. };
  86543. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86544. if (DDSTools.StoreLODInAlphaChannel) {
  86545. var destArray = new Uint16Array(dataLength);
  86546. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86547. var index = 0;
  86548. for (var y = 0; y < height; y++) {
  86549. for (var x = 0; x < width; x++) {
  86550. var srcPos = (x + y * width) * 4;
  86551. destArray[index] = srcData[srcPos];
  86552. destArray[index + 1] = srcData[srcPos + 1];
  86553. destArray[index + 2] = srcData[srcPos + 2];
  86554. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86555. index += 4;
  86556. }
  86557. }
  86558. return destArray;
  86559. }
  86560. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86561. };
  86562. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86563. if (DDSTools.StoreLODInAlphaChannel) {
  86564. var destArray = new Float32Array(dataLength);
  86565. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86566. var index = 0;
  86567. for (var y = 0; y < height; y++) {
  86568. for (var x = 0; x < width; x++) {
  86569. var srcPos = (x + y * width) * 4;
  86570. destArray[index] = srcData[srcPos];
  86571. destArray[index + 1] = srcData[srcPos + 1];
  86572. destArray[index + 2] = srcData[srcPos + 2];
  86573. destArray[index + 3] = lod;
  86574. index += 4;
  86575. }
  86576. }
  86577. return destArray;
  86578. }
  86579. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86580. };
  86581. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86582. var destArray = new Uint8Array(dataLength);
  86583. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86584. var index = 0;
  86585. for (var y = 0; y < height; y++) {
  86586. for (var x = 0; x < width; x++) {
  86587. var srcPos = (x + y * width) * 4;
  86588. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86589. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86590. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86591. if (DDSTools.StoreLODInAlphaChannel) {
  86592. destArray[index + 3] = lod;
  86593. }
  86594. else {
  86595. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86596. }
  86597. index += 4;
  86598. }
  86599. }
  86600. return destArray;
  86601. };
  86602. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86603. var destArray = new Uint8Array(dataLength);
  86604. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86605. var index = 0;
  86606. for (var y = 0; y < height; y++) {
  86607. for (var x = 0; x < width; x++) {
  86608. var srcPos = (x + y * width) * 4;
  86609. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86610. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86611. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86612. if (DDSTools.StoreLODInAlphaChannel) {
  86613. destArray[index + 3] = lod;
  86614. }
  86615. else {
  86616. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86617. }
  86618. index += 4;
  86619. }
  86620. }
  86621. return destArray;
  86622. };
  86623. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86624. var byteArray = new Uint8Array(dataLength);
  86625. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86626. var index = 0;
  86627. for (var y = 0; y < height; y++) {
  86628. for (var x = 0; x < width; x++) {
  86629. var srcPos = (x + y * width) * 4;
  86630. byteArray[index] = srcData[srcPos + rOffset];
  86631. byteArray[index + 1] = srcData[srcPos + gOffset];
  86632. byteArray[index + 2] = srcData[srcPos + bOffset];
  86633. byteArray[index + 3] = srcData[srcPos + aOffset];
  86634. index += 4;
  86635. }
  86636. }
  86637. return byteArray;
  86638. };
  86639. DDSTools._ExtractLongWordOrder = function (value) {
  86640. if (value === 0 || value === 255 || value === -16777216) {
  86641. return 0;
  86642. }
  86643. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86644. };
  86645. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86646. var byteArray = new Uint8Array(dataLength);
  86647. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86648. var index = 0;
  86649. for (var y = 0; y < height; y++) {
  86650. for (var x = 0; x < width; x++) {
  86651. var srcPos = (x + y * width) * 3;
  86652. byteArray[index] = srcData[srcPos + rOffset];
  86653. byteArray[index + 1] = srcData[srcPos + gOffset];
  86654. byteArray[index + 2] = srcData[srcPos + bOffset];
  86655. index += 3;
  86656. }
  86657. }
  86658. return byteArray;
  86659. };
  86660. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86661. var byteArray = new Uint8Array(dataLength);
  86662. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86663. var index = 0;
  86664. for (var y = 0; y < height; y++) {
  86665. for (var x = 0; x < width; x++) {
  86666. var srcPos = (x + y * width);
  86667. byteArray[index] = srcData[srcPos];
  86668. index++;
  86669. }
  86670. }
  86671. return byteArray;
  86672. };
  86673. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86674. if (lodIndex === void 0) { lodIndex = -1; }
  86675. var sphericalPolynomialFaces = null;
  86676. if (info.sphericalPolynomial) {
  86677. sphericalPolynomialFaces = new Array();
  86678. }
  86679. var ext = engine.getCaps().s3tc;
  86680. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86681. var fourCC, width, height, dataLength = 0, dataOffset;
  86682. var byteArray, mipmapCount, mip;
  86683. var internalFormat = 0;
  86684. var format = 0;
  86685. var blockBytes = 1;
  86686. if (header[off_magic] !== DDS_MAGIC) {
  86687. BABYLON.Tools.Error("Invalid magic number in DDS header");
  86688. return;
  86689. }
  86690. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  86691. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  86692. return;
  86693. }
  86694. if (info.isCompressed && !ext) {
  86695. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  86696. return;
  86697. }
  86698. var bpp = header[off_RGBbpp];
  86699. dataOffset = header[off_size] + 4;
  86700. var computeFormats = false;
  86701. if (info.isFourCC) {
  86702. fourCC = header[off_pfFourCC];
  86703. switch (fourCC) {
  86704. case FOURCC_DXT1:
  86705. blockBytes = 8;
  86706. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  86707. break;
  86708. case FOURCC_DXT3:
  86709. blockBytes = 16;
  86710. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  86711. break;
  86712. case FOURCC_DXT5:
  86713. blockBytes = 16;
  86714. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  86715. break;
  86716. case FOURCC_D3DFMT_R16G16B16A16F:
  86717. computeFormats = true;
  86718. break;
  86719. case FOURCC_D3DFMT_R32G32B32A32F:
  86720. computeFormats = true;
  86721. break;
  86722. case FOURCC_DX10:
  86723. // There is an additionnal header so dataOffset need to be changed
  86724. dataOffset += 5 * 4; // 5 uints
  86725. var supported = false;
  86726. switch (info.dxgiFormat) {
  86727. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  86728. computeFormats = true;
  86729. supported = true;
  86730. break;
  86731. case DXGI_FORMAT_B8G8R8X8_UNORM:
  86732. info.isRGB = true;
  86733. info.isFourCC = false;
  86734. bpp = 32;
  86735. supported = true;
  86736. break;
  86737. }
  86738. if (supported) {
  86739. break;
  86740. }
  86741. default:
  86742. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  86743. return;
  86744. }
  86745. }
  86746. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  86747. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  86748. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  86749. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  86750. if (computeFormats) {
  86751. format = engine._getWebGLTextureType(info.textureType);
  86752. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86753. }
  86754. mipmapCount = 1;
  86755. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  86756. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86757. }
  86758. for (var face = 0; face < faces; face++) {
  86759. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  86760. width = header[off_width];
  86761. height = header[off_height];
  86762. for (mip = 0; mip < mipmapCount; ++mip) {
  86763. if (lodIndex === -1 || lodIndex === mip) {
  86764. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  86765. var i = (lodIndex === -1) ? mip : 0;
  86766. if (!info.isCompressed && info.isFourCC) {
  86767. dataLength = width * height * 4;
  86768. var floatArray = null;
  86769. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  86770. if (bpp === 128) {
  86771. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86772. if (sphericalPolynomialFaces && i == 0) {
  86773. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86774. }
  86775. }
  86776. else if (bpp === 64) {
  86777. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86778. if (sphericalPolynomialFaces && i == 0) {
  86779. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86780. }
  86781. }
  86782. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86783. format = engine._getWebGLTextureType(info.textureType);
  86784. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86785. }
  86786. else {
  86787. if (bpp === 128) {
  86788. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86789. if (sphericalPolynomialFaces && i == 0) {
  86790. sphericalPolynomialFaces.push(floatArray);
  86791. }
  86792. }
  86793. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  86794. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86795. if (sphericalPolynomialFaces && i == 0) {
  86796. sphericalPolynomialFaces.push(floatArray);
  86797. }
  86798. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86799. format = engine._getWebGLTextureType(info.textureType);
  86800. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  86801. }
  86802. else { // 64
  86803. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  86804. if (sphericalPolynomialFaces && i == 0) {
  86805. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  86806. }
  86807. }
  86808. }
  86809. if (floatArray) {
  86810. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  86811. }
  86812. }
  86813. else if (info.isRGB) {
  86814. if (bpp === 24) {
  86815. dataLength = width * height * 3;
  86816. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  86817. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  86818. }
  86819. else { // 32
  86820. dataLength = width * height * 4;
  86821. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  86822. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  86823. }
  86824. }
  86825. else if (info.isLuminance) {
  86826. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  86827. var unpaddedRowSize = width;
  86828. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  86829. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  86830. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  86831. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  86832. }
  86833. else {
  86834. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  86835. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  86836. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  86837. }
  86838. }
  86839. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  86840. width *= 0.5;
  86841. height *= 0.5;
  86842. width = Math.max(1.0, width);
  86843. height = Math.max(1.0, height);
  86844. }
  86845. if (currentFace !== undefined) {
  86846. // Loading a single face
  86847. break;
  86848. }
  86849. }
  86850. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  86851. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  86852. size: header[off_width],
  86853. right: sphericalPolynomialFaces[0],
  86854. left: sphericalPolynomialFaces[1],
  86855. up: sphericalPolynomialFaces[2],
  86856. down: sphericalPolynomialFaces[3],
  86857. front: sphericalPolynomialFaces[4],
  86858. back: sphericalPolynomialFaces[5],
  86859. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  86860. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  86861. gammaSpace: false,
  86862. });
  86863. }
  86864. else {
  86865. info.sphericalPolynomial = undefined;
  86866. }
  86867. };
  86868. DDSTools.StoreLODInAlphaChannel = false;
  86869. return DDSTools;
  86870. }());
  86871. BABYLON.DDSTools = DDSTools;
  86872. })(BABYLON || (BABYLON = {}));
  86873. //# sourceMappingURL=babylon.dds.js.map
  86874. var BABYLON;
  86875. (function (BABYLON) {
  86876. /**
  86877. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  86878. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  86879. */
  86880. var KhronosTextureContainer = /** @class */ (function () {
  86881. /**
  86882. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  86883. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  86884. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  86885. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  86886. */
  86887. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  86888. this.arrayBuffer = arrayBuffer;
  86889. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  86890. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  86891. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  86892. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  86893. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  86894. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  86895. BABYLON.Tools.Error("texture missing KTX identifier");
  86896. return;
  86897. }
  86898. // load the reset of the header in native 32 bit int
  86899. var header = new Int32Array(this.arrayBuffer, 12, 13);
  86900. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  86901. var oppositeEndianess = header[0] === 0x01020304;
  86902. // read all the header elements in order they exist in the file, without modification (sans endainness)
  86903. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  86904. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  86905. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  86906. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  86907. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  86908. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  86909. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  86910. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  86911. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  86912. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  86913. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  86914. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  86915. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  86916. if (this.glType !== 0) {
  86917. BABYLON.Tools.Error("only compressed formats currently supported");
  86918. return;
  86919. }
  86920. else {
  86921. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  86922. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  86923. }
  86924. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  86925. BABYLON.Tools.Error("only 2D textures currently supported");
  86926. return;
  86927. }
  86928. if (this.numberOfArrayElements !== 0) {
  86929. BABYLON.Tools.Error("texture arrays not currently supported");
  86930. return;
  86931. }
  86932. if (this.numberOfFaces !== facesExpected) {
  86933. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  86934. return;
  86935. }
  86936. // we now have a completely validated file, so could use existence of loadType as success
  86937. // would need to make this more elaborate & adjust checks above to support more than one load type
  86938. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  86939. }
  86940. // not as fast hardware based, but will probably never need to use
  86941. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  86942. return ((val & 0xFF) << 24)
  86943. | ((val & 0xFF00) << 8)
  86944. | ((val >> 8) & 0xFF00)
  86945. | ((val >> 24) & 0xFF);
  86946. };
  86947. /**
  86948. * It is assumed that the texture has already been created & is currently bound
  86949. */
  86950. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  86951. switch (this.loadType) {
  86952. case KhronosTextureContainer.COMPRESSED_2D:
  86953. this._upload2DCompressedLevels(gl, loadMipmaps);
  86954. break;
  86955. case KhronosTextureContainer.TEX_2D:
  86956. case KhronosTextureContainer.COMPRESSED_3D:
  86957. case KhronosTextureContainer.TEX_3D:
  86958. }
  86959. };
  86960. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  86961. // initialize width & height for level 1
  86962. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  86963. var width = this.pixelWidth;
  86964. var height = this.pixelHeight;
  86965. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  86966. for (var level = 0; level < mipmapCount; level++) {
  86967. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  86968. for (var face = 0; face < this.numberOfFaces; face++) {
  86969. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  86970. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  86971. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  86972. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  86973. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  86974. }
  86975. width = Math.max(1.0, width * 0.5);
  86976. height = Math.max(1.0, height * 0.5);
  86977. }
  86978. };
  86979. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  86980. // load types
  86981. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  86982. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  86983. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  86984. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  86985. return KhronosTextureContainer;
  86986. }());
  86987. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  86988. })(BABYLON || (BABYLON = {}));
  86989. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  86990. var BABYLON;
  86991. (function (BABYLON) {
  86992. var Debug;
  86993. (function (Debug) {
  86994. /**
  86995. * Class used to render a debug view of a given skeleton
  86996. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  86997. */
  86998. var SkeletonViewer = /** @class */ (function () {
  86999. /**
  87000. * Creates a new SkeletonViewer
  87001. * @param skeleton defines the skeleton to render
  87002. * @param mesh defines the mesh attached to the skeleton
  87003. * @param scene defines the hosting scene
  87004. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87005. * @param renderingGroupId defines the rendering group id to use with the viewer
  87006. */
  87007. function SkeletonViewer(
  87008. /** defines the skeleton to render */
  87009. skeleton,
  87010. /** defines the mesh attached to the skeleton */
  87011. mesh, scene,
  87012. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87013. autoUpdateBonesMatrices,
  87014. /** defines the rendering group id to use with the viewer */
  87015. renderingGroupId) {
  87016. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87017. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87018. this.skeleton = skeleton;
  87019. this.mesh = mesh;
  87020. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87021. this.renderingGroupId = renderingGroupId;
  87022. /** Gets or sets the color used to render the skeleton */
  87023. this.color = BABYLON.Color3.White();
  87024. this._debugLines = new Array();
  87025. this._isEnabled = false;
  87026. this._scene = scene;
  87027. this.update();
  87028. this._renderFunction = this.update.bind(this);
  87029. }
  87030. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87031. get: function () {
  87032. return this._isEnabled;
  87033. },
  87034. /** Gets or sets a boolean indicating if the viewer is enabled */
  87035. set: function (value) {
  87036. if (this._isEnabled === value) {
  87037. return;
  87038. }
  87039. this._isEnabled = value;
  87040. if (value) {
  87041. this._scene.registerBeforeRender(this._renderFunction);
  87042. }
  87043. else {
  87044. this._scene.unregisterBeforeRender(this._renderFunction);
  87045. }
  87046. },
  87047. enumerable: true,
  87048. configurable: true
  87049. });
  87050. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87051. if (x === void 0) { x = 0; }
  87052. if (y === void 0) { y = 0; }
  87053. if (z === void 0) { z = 0; }
  87054. var tmat = BABYLON.Tmp.Matrix[0];
  87055. var parentBone = bone.getParent();
  87056. tmat.copyFrom(bone.getLocalMatrix());
  87057. if (x !== 0 || y !== 0 || z !== 0) {
  87058. var tmat2 = BABYLON.Tmp.Matrix[1];
  87059. BABYLON.Matrix.IdentityToRef(tmat2);
  87060. tmat2.m[12] = x;
  87061. tmat2.m[13] = y;
  87062. tmat2.m[14] = z;
  87063. tmat2.multiplyToRef(tmat, tmat);
  87064. }
  87065. if (parentBone) {
  87066. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87067. }
  87068. tmat.multiplyToRef(meshMat, tmat);
  87069. position.x = tmat.m[12];
  87070. position.y = tmat.m[13];
  87071. position.z = tmat.m[14];
  87072. };
  87073. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87074. var len = bones.length;
  87075. var meshPos = this.mesh.position;
  87076. for (var i = 0; i < len; i++) {
  87077. var bone = bones[i];
  87078. var points = this._debugLines[i];
  87079. if (!points) {
  87080. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87081. this._debugLines[i] = points;
  87082. }
  87083. this._getBonePosition(points[0], bone, meshMat);
  87084. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87085. points[0].subtractInPlace(meshPos);
  87086. points[1].subtractInPlace(meshPos);
  87087. }
  87088. };
  87089. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87090. var len = bones.length;
  87091. var boneNum = 0;
  87092. var meshPos = this.mesh.position;
  87093. for (var i = len - 1; i >= 0; i--) {
  87094. var childBone = bones[i];
  87095. var parentBone = childBone.getParent();
  87096. if (!parentBone) {
  87097. continue;
  87098. }
  87099. var points = this._debugLines[boneNum];
  87100. if (!points) {
  87101. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87102. this._debugLines[boneNum] = points;
  87103. }
  87104. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87105. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87106. points[0].subtractInPlace(meshPos);
  87107. points[1].subtractInPlace(meshPos);
  87108. boneNum++;
  87109. }
  87110. };
  87111. /** Update the viewer to sync with current skeleton state */
  87112. SkeletonViewer.prototype.update = function () {
  87113. if (this.autoUpdateBonesMatrices) {
  87114. this.skeleton.computeAbsoluteTransforms();
  87115. }
  87116. if (this.skeleton.bones[0].length === undefined) {
  87117. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87118. }
  87119. else {
  87120. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87121. }
  87122. if (!this._debugMesh) {
  87123. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87124. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87125. }
  87126. else {
  87127. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87128. }
  87129. this._debugMesh.position.copyFrom(this.mesh.position);
  87130. this._debugMesh.color = this.color;
  87131. };
  87132. /** Release associated resources */
  87133. SkeletonViewer.prototype.dispose = function () {
  87134. if (this._debugMesh) {
  87135. this.isEnabled = false;
  87136. this._debugMesh.dispose();
  87137. this._debugMesh = null;
  87138. }
  87139. };
  87140. return SkeletonViewer;
  87141. }());
  87142. Debug.SkeletonViewer = SkeletonViewer;
  87143. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87144. })(BABYLON || (BABYLON = {}));
  87145. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87146. /**
  87147. * Module Debug contains the (visual) components to debug a scene correctly
  87148. */
  87149. var BABYLON;
  87150. (function (BABYLON) {
  87151. var Debug;
  87152. (function (Debug) {
  87153. /**
  87154. * The Axes viewer will show 3 axes in a specific point in space
  87155. */
  87156. var AxesViewer = /** @class */ (function () {
  87157. /**
  87158. * Creates a new AxesViewer
  87159. * @param scene defines the hosting scene
  87160. * @param scaleLines defines a number used to scale line length (1 by default)
  87161. */
  87162. function AxesViewer(scene, scaleLines) {
  87163. if (scaleLines === void 0) { scaleLines = 1; }
  87164. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87165. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87166. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87167. /**
  87168. * Gets or sets a number used to scale line length
  87169. */
  87170. this.scaleLines = 1;
  87171. this.scaleLines = scaleLines;
  87172. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87173. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87174. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87175. this._xmesh.renderingGroupId = 2;
  87176. this._ymesh.renderingGroupId = 2;
  87177. this._zmesh.renderingGroupId = 2;
  87178. this._xmesh.material.checkReadyOnlyOnce = true;
  87179. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87180. this._ymesh.material.checkReadyOnlyOnce = true;
  87181. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87182. this._zmesh.material.checkReadyOnlyOnce = true;
  87183. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87184. this.scene = scene;
  87185. }
  87186. /**
  87187. * Force the viewer to update
  87188. * @param position defines the position of the viewer
  87189. * @param xaxis defines the x axis of the viewer
  87190. * @param yaxis defines the y axis of the viewer
  87191. * @param zaxis defines the z axis of the viewer
  87192. */
  87193. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87194. var scaleLines = this.scaleLines;
  87195. if (this._xmesh) {
  87196. this._xmesh.position.copyFrom(position);
  87197. }
  87198. if (this._ymesh) {
  87199. this._ymesh.position.copyFrom(position);
  87200. }
  87201. if (this._zmesh) {
  87202. this._zmesh.position.copyFrom(position);
  87203. }
  87204. var point2 = this._xline[1];
  87205. point2.x = xaxis.x * scaleLines;
  87206. point2.y = xaxis.y * scaleLines;
  87207. point2.z = xaxis.z * scaleLines;
  87208. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87209. point2 = this._yline[1];
  87210. point2.x = yaxis.x * scaleLines;
  87211. point2.y = yaxis.y * scaleLines;
  87212. point2.z = yaxis.z * scaleLines;
  87213. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87214. point2 = this._zline[1];
  87215. point2.x = zaxis.x * scaleLines;
  87216. point2.y = zaxis.y * scaleLines;
  87217. point2.z = zaxis.z * scaleLines;
  87218. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87219. };
  87220. /** Releases resources */
  87221. AxesViewer.prototype.dispose = function () {
  87222. if (this._xmesh) {
  87223. this._xmesh.dispose();
  87224. }
  87225. if (this._ymesh) {
  87226. this._ymesh.dispose();
  87227. }
  87228. if (this._zmesh) {
  87229. this._zmesh.dispose();
  87230. }
  87231. this._xmesh = null;
  87232. this._ymesh = null;
  87233. this._zmesh = null;
  87234. this.scene = null;
  87235. };
  87236. return AxesViewer;
  87237. }());
  87238. Debug.AxesViewer = AxesViewer;
  87239. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87240. })(BABYLON || (BABYLON = {}));
  87241. //# sourceMappingURL=babylon.axesViewer.js.map
  87242. var BABYLON;
  87243. (function (BABYLON) {
  87244. var Debug;
  87245. (function (Debug) {
  87246. /**
  87247. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87248. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87249. */
  87250. var BoneAxesViewer = /** @class */ (function (_super) {
  87251. __extends(BoneAxesViewer, _super);
  87252. /**
  87253. * Creates a new BoneAxesViewer
  87254. * @param scene defines the hosting scene
  87255. * @param bone defines the target bone
  87256. * @param mesh defines the target mesh
  87257. * @param scaleLines defines a scaling factor for line length (1 by default)
  87258. */
  87259. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87260. if (scaleLines === void 0) { scaleLines = 1; }
  87261. var _this = _super.call(this, scene, scaleLines) || this;
  87262. /** Gets current position */
  87263. _this.pos = BABYLON.Vector3.Zero();
  87264. /** Gets direction of X axis */
  87265. _this.xaxis = BABYLON.Vector3.Zero();
  87266. /** Gets direction of Y axis */
  87267. _this.yaxis = BABYLON.Vector3.Zero();
  87268. /** Gets direction of Z axis */
  87269. _this.zaxis = BABYLON.Vector3.Zero();
  87270. _this.mesh = mesh;
  87271. _this.bone = bone;
  87272. return _this;
  87273. }
  87274. /**
  87275. * Force the viewer to update
  87276. */
  87277. BoneAxesViewer.prototype.update = function () {
  87278. if (!this.mesh || !this.bone) {
  87279. return;
  87280. }
  87281. var bone = this.bone;
  87282. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87283. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87284. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87285. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87286. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87287. };
  87288. /** Releases resources */
  87289. BoneAxesViewer.prototype.dispose = function () {
  87290. if (this.mesh) {
  87291. this.mesh = null;
  87292. this.bone = null;
  87293. _super.prototype.dispose.call(this);
  87294. }
  87295. };
  87296. return BoneAxesViewer;
  87297. }(Debug.AxesViewer));
  87298. Debug.BoneAxesViewer = BoneAxesViewer;
  87299. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87300. })(BABYLON || (BABYLON = {}));
  87301. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87302. var BABYLON;
  87303. (function (BABYLON) {
  87304. var RayHelper = /** @class */ (function () {
  87305. function RayHelper(ray) {
  87306. this.ray = ray;
  87307. }
  87308. RayHelper.CreateAndShow = function (ray, scene, color) {
  87309. var helper = new RayHelper(ray);
  87310. helper.show(scene, color);
  87311. return helper;
  87312. };
  87313. RayHelper.prototype.show = function (scene, color) {
  87314. if (!this._renderFunction && this.ray) {
  87315. var ray = this.ray;
  87316. this._renderFunction = this._render.bind(this);
  87317. this._scene = scene;
  87318. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87319. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87320. if (this._renderFunction) {
  87321. this._scene.registerBeforeRender(this._renderFunction);
  87322. }
  87323. }
  87324. if (color && this._renderLine) {
  87325. this._renderLine.color.copyFrom(color);
  87326. }
  87327. };
  87328. RayHelper.prototype.hide = function () {
  87329. if (this._renderFunction && this._scene) {
  87330. this._scene.unregisterBeforeRender(this._renderFunction);
  87331. this._scene = null;
  87332. this._renderFunction = null;
  87333. if (this._renderLine) {
  87334. this._renderLine.dispose();
  87335. this._renderLine = null;
  87336. }
  87337. this._renderPoints = [];
  87338. }
  87339. };
  87340. RayHelper.prototype._render = function () {
  87341. var ray = this.ray;
  87342. if (!ray) {
  87343. return;
  87344. }
  87345. var point = this._renderPoints[1];
  87346. var len = Math.min(ray.length, 1000000);
  87347. point.copyFrom(ray.direction);
  87348. point.scaleInPlace(len);
  87349. point.addInPlace(ray.origin);
  87350. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87351. };
  87352. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87353. this._attachedToMesh = mesh;
  87354. var ray = this.ray;
  87355. if (!ray) {
  87356. return;
  87357. }
  87358. if (!ray.direction) {
  87359. ray.direction = BABYLON.Vector3.Zero();
  87360. }
  87361. if (!ray.origin) {
  87362. ray.origin = BABYLON.Vector3.Zero();
  87363. }
  87364. if (length) {
  87365. ray.length = length;
  87366. }
  87367. if (!meshSpaceOrigin) {
  87368. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87369. }
  87370. if (!meshSpaceDirection) {
  87371. // -1 so that this will work with Mesh.lookAt
  87372. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87373. }
  87374. if (!this._meshSpaceDirection) {
  87375. this._meshSpaceDirection = meshSpaceDirection.clone();
  87376. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87377. }
  87378. else {
  87379. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87380. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87381. }
  87382. if (!this._updateToMeshFunction) {
  87383. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87384. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87385. }
  87386. this._updateToMesh();
  87387. };
  87388. RayHelper.prototype.detachFromMesh = function () {
  87389. if (this._attachedToMesh) {
  87390. if (this._updateToMeshFunction) {
  87391. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87392. }
  87393. this._attachedToMesh = null;
  87394. this._updateToMeshFunction = null;
  87395. }
  87396. };
  87397. RayHelper.prototype._updateToMesh = function () {
  87398. var ray = this.ray;
  87399. if (!this._attachedToMesh || !ray) {
  87400. return;
  87401. }
  87402. if (this._attachedToMesh._isDisposed) {
  87403. this.detachFromMesh();
  87404. return;
  87405. }
  87406. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87407. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87408. };
  87409. RayHelper.prototype.dispose = function () {
  87410. this.hide();
  87411. this.detachFromMesh();
  87412. this.ray = null;
  87413. };
  87414. return RayHelper;
  87415. }());
  87416. BABYLON.RayHelper = RayHelper;
  87417. })(BABYLON || (BABYLON = {}));
  87418. //# sourceMappingURL=babylon.rayHelper.js.map
  87419. var BABYLON;
  87420. (function (BABYLON) {
  87421. // load the inspector using require, if not present in the global namespace.
  87422. var DebugLayer = /** @class */ (function () {
  87423. function DebugLayer(scene) {
  87424. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87425. this._scene = scene;
  87426. // load inspector using require, if it doesn't exist on the global namespace.
  87427. }
  87428. /** Creates the inspector window. */
  87429. DebugLayer.prototype._createInspector = function (config) {
  87430. if (config === void 0) { config = {}; }
  87431. var popup = config.popup || false;
  87432. var initialTab = config.initialTab || 0;
  87433. var parentElement = config.parentElement || null;
  87434. if (!this._inspector) {
  87435. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87436. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87437. } // else nothing to do,; instance is already existing
  87438. };
  87439. DebugLayer.prototype.isVisible = function () {
  87440. if (!this._inspector) {
  87441. return false;
  87442. }
  87443. return true;
  87444. };
  87445. DebugLayer.prototype.hide = function () {
  87446. if (this._inspector) {
  87447. try {
  87448. this._inspector.dispose();
  87449. }
  87450. catch (e) {
  87451. // If the inspector has been removed directly from the inspector tool
  87452. }
  87453. this.onPropertyChangedObservable.clear();
  87454. this._inspector = null;
  87455. }
  87456. };
  87457. /**
  87458. *
  87459. * Launch the debugLayer.
  87460. *
  87461. * initialTab:
  87462. * | Value | Tab Name |
  87463. * | --- | --- |
  87464. * | 0 | Scene |
  87465. * | 1 | Console |
  87466. * | 2 | Stats |
  87467. * | 3 | Textures |
  87468. * | 4 | Mesh |
  87469. * | 5 | Light |
  87470. * | 6 | Material |
  87471. * | 7 | GLTF |
  87472. * | 8 | GUI |
  87473. * | 9 | Physics |
  87474. * | 10 | Camera |
  87475. * | 11 | Audio |
  87476. *
  87477. */
  87478. DebugLayer.prototype.show = function (config) {
  87479. if (config === void 0) { config = {}; }
  87480. if (typeof this.BJSINSPECTOR == 'undefined') {
  87481. // Load inspector and add it to the DOM
  87482. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87483. }
  87484. else {
  87485. // Otherwise creates the inspector
  87486. this._createInspector(config);
  87487. this.onPropertyChangedObservable = new BABYLON.Observable();
  87488. }
  87489. };
  87490. /**
  87491. * Gets the active tab
  87492. * @return the index of the active tab or -1 if the inspector is hidden
  87493. */
  87494. DebugLayer.prototype.getActiveTab = function () {
  87495. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87496. };
  87497. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87498. return DebugLayer;
  87499. }());
  87500. BABYLON.DebugLayer = DebugLayer;
  87501. })(BABYLON || (BABYLON = {}));
  87502. //# sourceMappingURL=babylon.debugLayer.js.map
  87503. var BABYLON;
  87504. (function (BABYLON) {
  87505. var Debug;
  87506. (function (Debug) {
  87507. /**
  87508. * Used to show the physics impostor around the specific mesh
  87509. */
  87510. var PhysicsViewer = /** @class */ (function () {
  87511. /**
  87512. * Creates a new PhysicsViewer
  87513. * @param scene defines the hosting scene
  87514. */
  87515. function PhysicsViewer(scene) {
  87516. /** @hidden */
  87517. this._impostors = [];
  87518. /** @hidden */
  87519. this._meshes = [];
  87520. /** @hidden */
  87521. this._numMeshes = 0;
  87522. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87523. var physicEngine = this._scene.getPhysicsEngine();
  87524. if (physicEngine) {
  87525. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87526. }
  87527. }
  87528. /** @hidden */
  87529. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87530. var plugin = this._physicsEnginePlugin;
  87531. for (var i = 0; i < this._numMeshes; i++) {
  87532. var impostor = this._impostors[i];
  87533. if (!impostor) {
  87534. continue;
  87535. }
  87536. if (impostor.isDisposed) {
  87537. this.hideImpostor(this._impostors[i--]);
  87538. }
  87539. else {
  87540. var mesh = this._meshes[i];
  87541. if (mesh && plugin) {
  87542. plugin.syncMeshWithImpostor(mesh, impostor);
  87543. }
  87544. }
  87545. }
  87546. };
  87547. /**
  87548. * Renders a specified physic impostor
  87549. * @param impostor defines the impostor to render
  87550. */
  87551. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87552. if (!this._scene) {
  87553. return;
  87554. }
  87555. for (var i = 0; i < this._numMeshes; i++) {
  87556. if (this._impostors[i] == impostor) {
  87557. return;
  87558. }
  87559. }
  87560. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87561. if (debugMesh) {
  87562. this._impostors[this._numMeshes] = impostor;
  87563. this._meshes[this._numMeshes] = debugMesh;
  87564. if (this._numMeshes === 0) {
  87565. this._renderFunction = this._updateDebugMeshes.bind(this);
  87566. this._scene.registerBeforeRender(this._renderFunction);
  87567. }
  87568. this._numMeshes++;
  87569. }
  87570. };
  87571. /**
  87572. * Hides a specified physic impostor
  87573. * @param impostor defines the impostor to hide
  87574. */
  87575. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87576. if (!impostor || !this._scene) {
  87577. return;
  87578. }
  87579. var removed = false;
  87580. for (var i = 0; i < this._numMeshes; i++) {
  87581. if (this._impostors[i] == impostor) {
  87582. var mesh = this._meshes[i];
  87583. if (!mesh) {
  87584. continue;
  87585. }
  87586. this._scene.removeMesh(mesh);
  87587. mesh.dispose();
  87588. this._numMeshes--;
  87589. if (this._numMeshes > 0) {
  87590. this._meshes[i] = this._meshes[this._numMeshes];
  87591. this._impostors[i] = this._impostors[this._numMeshes];
  87592. this._meshes[this._numMeshes] = null;
  87593. this._impostors[this._numMeshes] = null;
  87594. }
  87595. else {
  87596. this._meshes[0] = null;
  87597. this._impostors[0] = null;
  87598. }
  87599. removed = true;
  87600. break;
  87601. }
  87602. }
  87603. if (removed && this._numMeshes === 0) {
  87604. this._scene.unregisterBeforeRender(this._renderFunction);
  87605. }
  87606. };
  87607. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87608. if (!this._debugMaterial) {
  87609. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87610. this._debugMaterial.wireframe = true;
  87611. }
  87612. return this._debugMaterial;
  87613. };
  87614. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87615. if (!this._debugBoxMesh) {
  87616. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87617. this._debugBoxMesh.renderingGroupId = 1;
  87618. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87619. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87620. scene.removeMesh(this._debugBoxMesh);
  87621. }
  87622. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87623. };
  87624. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87625. if (!this._debugSphereMesh) {
  87626. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87627. this._debugSphereMesh.renderingGroupId = 1;
  87628. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87629. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87630. scene.removeMesh(this._debugSphereMesh);
  87631. }
  87632. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87633. };
  87634. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87635. var mesh = null;
  87636. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87637. mesh = this._getDebugBoxMesh(scene);
  87638. impostor.getBoxSizeToRef(mesh.scaling);
  87639. }
  87640. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87641. mesh = this._getDebugSphereMesh(scene);
  87642. var radius = impostor.getRadius();
  87643. mesh.scaling.x = radius * 2;
  87644. mesh.scaling.y = radius * 2;
  87645. mesh.scaling.z = radius * 2;
  87646. }
  87647. return mesh;
  87648. };
  87649. /** Releases all resources */
  87650. PhysicsViewer.prototype.dispose = function () {
  87651. for (var i = 0; i < this._numMeshes; i++) {
  87652. this.hideImpostor(this._impostors[i]);
  87653. }
  87654. if (this._debugBoxMesh) {
  87655. this._debugBoxMesh.dispose();
  87656. }
  87657. if (this._debugSphereMesh) {
  87658. this._debugSphereMesh.dispose();
  87659. }
  87660. if (this._debugMaterial) {
  87661. this._debugMaterial.dispose();
  87662. }
  87663. this._impostors.length = 0;
  87664. this._scene = null;
  87665. this._physicsEnginePlugin = null;
  87666. };
  87667. return PhysicsViewer;
  87668. }());
  87669. Debug.PhysicsViewer = PhysicsViewer;
  87670. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87671. })(BABYLON || (BABYLON = {}));
  87672. //# sourceMappingURL=babylon.physicsViewer.js.map
  87673. var BABYLON;
  87674. (function (BABYLON) {
  87675. var BoundingBoxRenderer = /** @class */ (function () {
  87676. function BoundingBoxRenderer(scene) {
  87677. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87678. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87679. this.showBackLines = true;
  87680. this.renderList = new BABYLON.SmartArray(32);
  87681. this._vertexBuffers = {};
  87682. this._scene = scene;
  87683. }
  87684. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87685. if (this._colorShader) {
  87686. return;
  87687. }
  87688. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  87689. attributes: [BABYLON.VertexBuffer.PositionKind],
  87690. uniforms: ["world", "viewProjection", "color"]
  87691. });
  87692. var engine = this._scene.getEngine();
  87693. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  87694. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  87695. this._createIndexBuffer();
  87696. };
  87697. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  87698. var engine = this._scene.getEngine();
  87699. 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]);
  87700. };
  87701. BoundingBoxRenderer.prototype._rebuild = function () {
  87702. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87703. if (vb) {
  87704. vb._rebuild();
  87705. }
  87706. this._createIndexBuffer();
  87707. };
  87708. BoundingBoxRenderer.prototype.reset = function () {
  87709. this.renderList.reset();
  87710. };
  87711. BoundingBoxRenderer.prototype.render = function () {
  87712. if (this.renderList.length === 0) {
  87713. return;
  87714. }
  87715. this._prepareRessources();
  87716. if (!this._colorShader.isReady()) {
  87717. return;
  87718. }
  87719. var engine = this._scene.getEngine();
  87720. engine.setDepthWrite(false);
  87721. this._colorShader._preBind();
  87722. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  87723. var boundingBox = this.renderList.data[boundingBoxIndex];
  87724. var min = boundingBox.minimum;
  87725. var max = boundingBox.maximum;
  87726. var diff = max.subtract(min);
  87727. var median = min.add(diff.scale(0.5));
  87728. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87729. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87730. .multiply(boundingBox.getWorldMatrix());
  87731. // VBOs
  87732. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87733. if (this.showBackLines) {
  87734. // Back
  87735. engine.setDepthFunctionToGreaterOrEqual();
  87736. this._scene.resetCachedMaterial();
  87737. this._colorShader.setColor4("color", this.backColor.toColor4());
  87738. this._colorShader.bind(worldMatrix);
  87739. // Draw order
  87740. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87741. }
  87742. // Front
  87743. engine.setDepthFunctionToLess();
  87744. this._scene.resetCachedMaterial();
  87745. this._colorShader.setColor4("color", this.frontColor.toColor4());
  87746. this._colorShader.bind(worldMatrix);
  87747. // Draw order
  87748. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87749. }
  87750. this._colorShader.unbind();
  87751. engine.setDepthFunctionToLessOrEqual();
  87752. engine.setDepthWrite(true);
  87753. };
  87754. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  87755. this._prepareRessources();
  87756. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  87757. return;
  87758. }
  87759. var engine = this._scene.getEngine();
  87760. engine.setDepthWrite(false);
  87761. engine.setColorWrite(false);
  87762. this._colorShader._preBind();
  87763. var boundingBox = mesh._boundingInfo.boundingBox;
  87764. var min = boundingBox.minimum;
  87765. var max = boundingBox.maximum;
  87766. var diff = max.subtract(min);
  87767. var median = min.add(diff.scale(0.5));
  87768. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  87769. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  87770. .multiply(boundingBox.getWorldMatrix());
  87771. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  87772. engine.setDepthFunctionToLess();
  87773. this._scene.resetCachedMaterial();
  87774. this._colorShader.bind(worldMatrix);
  87775. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  87776. this._colorShader.unbind();
  87777. engine.setDepthFunctionToLessOrEqual();
  87778. engine.setDepthWrite(true);
  87779. engine.setColorWrite(true);
  87780. };
  87781. BoundingBoxRenderer.prototype.dispose = function () {
  87782. if (!this._colorShader) {
  87783. return;
  87784. }
  87785. this.renderList.dispose();
  87786. this._colorShader.dispose();
  87787. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  87788. if (buffer) {
  87789. buffer.dispose();
  87790. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  87791. }
  87792. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  87793. };
  87794. return BoundingBoxRenderer;
  87795. }());
  87796. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  87797. })(BABYLON || (BABYLON = {}));
  87798. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  87799. var BABYLON;
  87800. (function (BABYLON) {
  87801. /**
  87802. * Renders a layer on top of an existing scene
  87803. */
  87804. var UtilityLayerRenderer = /** @class */ (function () {
  87805. /**
  87806. * Instantiates a UtilityLayerRenderer
  87807. * @param originalScene the original scene that will be rendered on top of
  87808. */
  87809. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  87810. var _this = this;
  87811. this.originalScene = originalScene;
  87812. this._pointerCaptures = {};
  87813. this._lastPointerEvents = {};
  87814. /**
  87815. * If the utility layer should automatically be rendered on top of existing scene
  87816. */
  87817. this.shouldRender = true;
  87818. /**
  87819. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  87820. */
  87821. this.onlyCheckPointerDownEvents = true;
  87822. /**
  87823. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  87824. */
  87825. this.processAllEvents = false;
  87826. /**
  87827. * Observable raised when the pointer move from the utility layer scene to the main scene
  87828. */
  87829. this.onPointerOutObservable = new BABYLON.Observable();
  87830. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  87831. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  87832. originalScene.getEngine().scenes.pop();
  87833. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  87834. this.utilityLayerScene.detachControl();
  87835. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  87836. if (!_this.processAllEvents) {
  87837. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  87838. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  87839. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  87840. return;
  87841. }
  87842. }
  87843. var pointerEvent = (prePointerInfo.event);
  87844. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  87845. return;
  87846. }
  87847. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  87848. if (!prePointerInfo.ray && utilityScenePick) {
  87849. prePointerInfo.ray = utilityScenePick.ray;
  87850. }
  87851. // always fire the prepointer oversvable
  87852. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  87853. // allow every non pointer down event to flow to the utility layer
  87854. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  87855. if (!prePointerInfo.skipOnPointerObservable) {
  87856. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87857. }
  87858. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  87859. _this._pointerCaptures[pointerEvent.pointerId] = false;
  87860. }
  87861. return;
  87862. }
  87863. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  87864. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  87865. if (utilityScenePick && utilityScenePick.hit) {
  87866. if (!prePointerInfo.skipOnPointerObservable) {
  87867. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  87868. }
  87869. prePointerInfo.skipOnPointerObservable = true;
  87870. }
  87871. }
  87872. else {
  87873. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  87874. var pointerEvent_1 = (prePointerInfo.event);
  87875. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  87876. if (originalScenePick && utilityScenePick) {
  87877. // No pick in utility scene
  87878. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  87879. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87880. // We touched an utility mesh present in the main scene
  87881. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87882. prePointerInfo.skipOnPointerObservable = true;
  87883. }
  87884. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  87885. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  87886. }
  87887. }
  87888. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  87889. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  87890. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  87891. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  87892. }
  87893. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  87894. // We have a pick in both scenes but main is closer than utility
  87895. // We touched an utility mesh present in the main scene
  87896. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  87897. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  87898. prePointerInfo.skipOnPointerObservable = true;
  87899. }
  87900. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  87901. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  87902. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  87903. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  87904. }
  87905. }
  87906. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  87907. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  87908. }
  87909. }
  87910. }
  87911. });
  87912. // Render directly on top of existing scene without clearing
  87913. this.utilityLayerScene.autoClear = false;
  87914. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  87915. if (_this.shouldRender) {
  87916. _this.render();
  87917. }
  87918. });
  87919. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  87920. _this.dispose();
  87921. });
  87922. this._updateCamera();
  87923. }
  87924. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  87925. if (!prePointerInfo.skipOnPointerObservable) {
  87926. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  87927. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  87928. }
  87929. };
  87930. /**
  87931. * Renders the utility layers scene on top of the original scene
  87932. */
  87933. UtilityLayerRenderer.prototype.render = function () {
  87934. this._updateCamera();
  87935. this.utilityLayerScene.render(false);
  87936. };
  87937. /**
  87938. * Disposes of the renderer
  87939. */
  87940. UtilityLayerRenderer.prototype.dispose = function () {
  87941. this.onPointerOutObservable.clear();
  87942. if (this._afterRenderObserver) {
  87943. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  87944. }
  87945. if (this._sceneDisposeObserver) {
  87946. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  87947. }
  87948. if (this._originalPointerObserver) {
  87949. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  87950. }
  87951. this.utilityLayerScene.dispose();
  87952. };
  87953. UtilityLayerRenderer.prototype._updateCamera = function () {
  87954. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  87955. };
  87956. return UtilityLayerRenderer;
  87957. }());
  87958. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  87959. })(BABYLON || (BABYLON = {}));
  87960. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  87961. //# sourceMappingURL=babylon.behavior.js.map
  87962. var BABYLON;
  87963. (function (BABYLON) {
  87964. /**
  87965. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  87966. */
  87967. var PointerDragBehavior = /** @class */ (function () {
  87968. /**
  87969. * Creates a pointer drag behavior that can be attached to a mesh
  87970. * @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)
  87971. */
  87972. function PointerDragBehavior(options) {
  87973. this.options = options;
  87974. /**
  87975. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  87976. */
  87977. this.currentDraggingPointerID = -1;
  87978. /**
  87979. * If the behavior is currently in a dragging state
  87980. */
  87981. this.dragging = false;
  87982. /**
  87983. * 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)
  87984. */
  87985. this.dragDeltaRatio = 0.2;
  87986. /**
  87987. * If the drag plane orientation should be updated during the dragging (Default: true)
  87988. */
  87989. this.updateDragPlane = true;
  87990. // Debug mode will display drag planes to help visualize behavior
  87991. this._debugMode = false;
  87992. this._moving = false;
  87993. /**
  87994. * Fires each time the attached mesh is dragged with the pointer
  87995. * * delta between last drag position and current drag position in world space
  87996. * * dragDistance along the drag axis
  87997. * * dragPlaneNormal normal of the current drag plane used during the drag
  87998. * * dragPlanePoint in world space where the drag intersects the drag plane
  87999. */
  88000. this.onDragObservable = new BABYLON.Observable();
  88001. /**
  88002. * Fires each time a drag begins (eg. mouse down on mesh)
  88003. */
  88004. this.onDragStartObservable = new BABYLON.Observable();
  88005. /**
  88006. * Fires each time a drag ends (eg. mouse release after drag)
  88007. */
  88008. this.onDragEndObservable = new BABYLON.Observable();
  88009. /**
  88010. * If the attached mesh should be moved when dragged
  88011. */
  88012. this.moveAttached = true;
  88013. /**
  88014. * If the drag behavior will react to drag events (Default: true)
  88015. */
  88016. this.enabled = true;
  88017. /**
  88018. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88019. */
  88020. this.useObjectOrienationForDragging = true;
  88021. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88022. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88023. // Variables to avoid instantiation in the below method
  88024. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88025. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88026. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88027. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88028. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88029. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88030. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88031. var optionCount = 0;
  88032. if (options === undefined) {
  88033. options = {};
  88034. }
  88035. if (options.dragAxis) {
  88036. optionCount++;
  88037. }
  88038. if (options.dragPlaneNormal) {
  88039. optionCount++;
  88040. }
  88041. if (optionCount > 1) {
  88042. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88043. }
  88044. }
  88045. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88046. /**
  88047. * The name of the behavior
  88048. */
  88049. get: function () {
  88050. return "PointerDrag";
  88051. },
  88052. enumerable: true,
  88053. configurable: true
  88054. });
  88055. /**
  88056. * Initializes the behavior
  88057. */
  88058. PointerDragBehavior.prototype.init = function () { };
  88059. /**
  88060. * Attaches the drag behavior the passed in mesh
  88061. * @param ownerNode The mesh that will be dragged around once attached
  88062. */
  88063. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88064. var _this = this;
  88065. this._scene = ownerNode.getScene();
  88066. this._attachedNode = ownerNode;
  88067. // Initialize drag plane to not interfere with existing scene
  88068. if (!PointerDragBehavior._planeScene) {
  88069. if (this._debugMode) {
  88070. PointerDragBehavior._planeScene = this._scene;
  88071. }
  88072. else {
  88073. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88074. this._scene.getEngine().scenes.pop();
  88075. }
  88076. }
  88077. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88078. // State of the drag
  88079. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88080. var delta = new BABYLON.Vector3(0, 0, 0);
  88081. var dragLength = 0;
  88082. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88083. var pickPredicate = function (m) {
  88084. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88085. };
  88086. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88087. if (!_this.enabled) {
  88088. return;
  88089. }
  88090. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88091. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88092. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88093. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88094. if (pickedPoint) {
  88095. _this.dragging = true;
  88096. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88097. _this.lastDragPosition.copyFrom(pickedPoint);
  88098. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88099. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88100. }
  88101. }
  88102. }
  88103. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88104. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88105. _this.releaseDrag();
  88106. }
  88107. }
  88108. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88109. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88110. _this._moving = true;
  88111. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88112. if (pickedPoint) {
  88113. if (_this.updateDragPlane) {
  88114. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88115. }
  88116. // depending on the drag mode option drag accordingly
  88117. if (_this.options.dragAxis) {
  88118. // Convert local drag axis to world
  88119. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88120. // Project delta drag from the drag plane onto the drag axis
  88121. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88122. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88123. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88124. }
  88125. else {
  88126. dragLength = delta.length();
  88127. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88128. }
  88129. targetPosition.addInPlace(delta);
  88130. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88131. _this.lastDragPosition.copyFrom(pickedPoint);
  88132. }
  88133. }
  88134. }
  88135. });
  88136. this._scene.onBeforeRenderObservable.add(function () {
  88137. if (_this._moving && _this.moveAttached) {
  88138. // Slowly move mesh to avoid jitter
  88139. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88140. _this._tmpVector.scaleInPlace(0.2);
  88141. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88142. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88143. }
  88144. });
  88145. };
  88146. PointerDragBehavior.prototype.releaseDrag = function () {
  88147. this.dragging = false;
  88148. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88149. this.currentDraggingPointerID = -1;
  88150. this._moving = false;
  88151. };
  88152. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88153. var _this = this;
  88154. if (!ray) {
  88155. return null;
  88156. }
  88157. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88158. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88159. return pickResult.pickedPoint;
  88160. }
  88161. else {
  88162. return null;
  88163. }
  88164. };
  88165. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88166. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88167. this._pointA.copyFrom(dragPlanePosition);
  88168. if (this.options.dragAxis) {
  88169. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88170. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88171. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88172. ray.origin.subtractToRef(this._pointA, this._pointC);
  88173. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88174. // Get perpendicular line from direction to camera and drag axis
  88175. this._pointB.subtractToRef(this._pointA, this._lineA);
  88176. this._pointC.subtractToRef(this._pointA, this._lineB);
  88177. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88178. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88179. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88180. this._lookAt.normalize();
  88181. this._dragPlane.position.copyFrom(this._pointA);
  88182. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88183. this._dragPlane.lookAt(this._lookAt);
  88184. }
  88185. else if (this.options.dragPlaneNormal) {
  88186. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88187. this._dragPlane.position.copyFrom(this._pointA);
  88188. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88189. this._dragPlane.lookAt(this._lookAt);
  88190. }
  88191. else {
  88192. this._dragPlane.position.copyFrom(this._pointA);
  88193. this._dragPlane.lookAt(ray.origin);
  88194. }
  88195. this._dragPlane.computeWorldMatrix(true);
  88196. };
  88197. /**
  88198. * Detaches the behavior from the mesh
  88199. */
  88200. PointerDragBehavior.prototype.detach = function () {
  88201. if (this._pointerObserver) {
  88202. this._scene.onPointerObservable.remove(this._pointerObserver);
  88203. }
  88204. };
  88205. return PointerDragBehavior;
  88206. }());
  88207. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88208. })(BABYLON || (BABYLON = {}));
  88209. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88210. var BABYLON;
  88211. (function (BABYLON) {
  88212. /**
  88213. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88214. */
  88215. var MultiPointerScaleBehavior = /** @class */ (function () {
  88216. function MultiPointerScaleBehavior() {
  88217. this._startDistance = 0;
  88218. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88219. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88220. this._sceneRenderObserver = null;
  88221. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88222. this._dragBehaviorA.moveAttached = false;
  88223. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88224. this._dragBehaviorB.moveAttached = false;
  88225. }
  88226. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88227. /**
  88228. * The name of the behavior
  88229. */
  88230. get: function () {
  88231. return "MultiPointerScale";
  88232. },
  88233. enumerable: true,
  88234. configurable: true
  88235. });
  88236. /**
  88237. * Initializes the behavior
  88238. */
  88239. MultiPointerScaleBehavior.prototype.init = function () { };
  88240. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88241. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88242. };
  88243. /**
  88244. * Attaches the scale behavior the passed in mesh
  88245. * @param ownerNode The mesh that will be scaled around once attached
  88246. */
  88247. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88248. var _this = this;
  88249. this._ownerNode = ownerNode;
  88250. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88251. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88252. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88253. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88254. _this._dragBehaviorA.releaseDrag();
  88255. }
  88256. else {
  88257. _this._initialScale.copyFrom(ownerNode.scaling);
  88258. _this._startDistance = _this._getCurrentDistance();
  88259. }
  88260. }
  88261. });
  88262. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88263. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88264. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88265. _this._dragBehaviorB.releaseDrag();
  88266. }
  88267. else {
  88268. _this._initialScale.copyFrom(ownerNode.scaling);
  88269. _this._startDistance = _this._getCurrentDistance();
  88270. }
  88271. }
  88272. });
  88273. // Once both drag behaviors are active scale based on the distance between the two pointers
  88274. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88275. behavior.onDragObservable.add(function () {
  88276. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88277. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88278. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88279. }
  88280. });
  88281. });
  88282. ownerNode.addBehavior(this._dragBehaviorA);
  88283. ownerNode.addBehavior(this._dragBehaviorB);
  88284. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88285. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88286. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88287. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88288. if (change.length() > 0.01) {
  88289. ownerNode.scaling.addInPlace(change);
  88290. }
  88291. }
  88292. });
  88293. };
  88294. /**
  88295. * Detaches the behavior from the mesh
  88296. */
  88297. MultiPointerScaleBehavior.prototype.detach = function () {
  88298. var _this = this;
  88299. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88300. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88301. behavior.onDragStartObservable.clear();
  88302. behavior.onDragObservable.clear();
  88303. _this._ownerNode.removeBehavior(behavior);
  88304. });
  88305. };
  88306. return MultiPointerScaleBehavior;
  88307. }());
  88308. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88309. })(BABYLON || (BABYLON = {}));
  88310. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88311. var BABYLON;
  88312. (function (BABYLON) {
  88313. /**
  88314. * 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
  88315. */
  88316. var SixDofDragBehavior = /** @class */ (function () {
  88317. function SixDofDragBehavior() {
  88318. this._sceneRenderObserver = null;
  88319. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88320. this._moving = false;
  88321. this._startingOrientation = new BABYLON.Quaternion();
  88322. /**
  88323. * 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: 5)
  88324. */
  88325. this.zDragFactor = 5;
  88326. /**
  88327. * If the behavior is currently in a dragging state
  88328. */
  88329. this.dragging = false;
  88330. /**
  88331. * 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)
  88332. */
  88333. this.dragDeltaRatio = 0.2;
  88334. /**
  88335. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88336. */
  88337. this.currentDraggingPointerID = -1;
  88338. }
  88339. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88340. /**
  88341. * The name of the behavior
  88342. */
  88343. get: function () {
  88344. return "SixDofDrag";
  88345. },
  88346. enumerable: true,
  88347. configurable: true
  88348. });
  88349. /**
  88350. * Initializes the behavior
  88351. */
  88352. SixDofDragBehavior.prototype.init = function () { };
  88353. /**
  88354. * Attaches the scale behavior the passed in mesh
  88355. * @param ownerNode The mesh that will be scaled around once attached
  88356. */
  88357. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88358. var _this = this;
  88359. this._ownerNode = ownerNode;
  88360. this._scene = this._ownerNode.getScene();
  88361. if (!SixDofDragBehavior._virtualScene) {
  88362. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88363. this._scene.getEngine().scenes.pop();
  88364. }
  88365. var pickedMesh = null;
  88366. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88367. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88368. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88369. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88370. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88371. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88372. var pickPredicate = function (m) {
  88373. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88374. };
  88375. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88376. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88377. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88378. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88379. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88380. // Set position and orientation of the controller
  88381. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88382. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88383. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88384. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88385. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88386. if (!pickedMesh.rotationQuaternion) {
  88387. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88388. }
  88389. var oldParent = pickedMesh.parent;
  88390. pickedMesh.setParent(null);
  88391. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88392. pickedMesh.setParent(oldParent);
  88393. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88394. // Update state
  88395. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88396. _this.dragging = true;
  88397. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88398. }
  88399. }
  88400. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88401. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88402. _this.dragging = false;
  88403. _this._moving = false;
  88404. _this.currentDraggingPointerID = -1;
  88405. pickedMesh = null;
  88406. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88407. }
  88408. }
  88409. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88410. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88411. // Calculate controller drag distance in controller space
  88412. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88413. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88414. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88415. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88416. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88417. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88418. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88419. if (_this._virtualDragMesh.position.z < 0) {
  88420. _this._virtualDragMesh.position.z = 0;
  88421. }
  88422. // Update the controller position
  88423. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88424. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88425. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88426. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88427. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88428. if (pickedMesh.parent) {
  88429. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88430. }
  88431. if (!_this._moving) {
  88432. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88433. }
  88434. _this._moving = true;
  88435. }
  88436. }
  88437. });
  88438. var tmpQuaternion = new BABYLON.Quaternion();
  88439. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88440. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88441. if (_this.dragging && _this._moving && pickedMesh) {
  88442. // Slowly move mesh to avoid jitter
  88443. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88444. // Get change in rotation
  88445. tmpQuaternion.copyFrom(_this._startingOrientation);
  88446. tmpQuaternion.x = -tmpQuaternion.x;
  88447. tmpQuaternion.y = -tmpQuaternion.y;
  88448. tmpQuaternion.z = -tmpQuaternion.z;
  88449. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88450. // Convert change in rotation to only y axis rotation
  88451. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88452. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88453. // Slowly move mesh to avoid jitter
  88454. var oldParent = pickedMesh.parent;
  88455. pickedMesh.setParent(null);
  88456. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88457. pickedMesh.setParent(oldParent);
  88458. }
  88459. });
  88460. };
  88461. /**
  88462. * Detaches the behavior from the mesh
  88463. */
  88464. SixDofDragBehavior.prototype.detach = function () {
  88465. this._scene.onPointerObservable.remove(this._pointerObserver);
  88466. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88467. this._virtualOriginMesh.dispose();
  88468. this._virtualDragMesh.dispose();
  88469. };
  88470. return SixDofDragBehavior;
  88471. }());
  88472. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88473. })(BABYLON || (BABYLON = {}));
  88474. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88475. var BABYLON;
  88476. (function (BABYLON) {
  88477. /**
  88478. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88479. */
  88480. var Gizmo = /** @class */ (function () {
  88481. /**
  88482. * Creates a gizmo
  88483. * @param gizmoLayer The utility layer the gizmo will be added to
  88484. */
  88485. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88486. var _this = this;
  88487. this.gizmoLayer = gizmoLayer;
  88488. /**
  88489. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88490. */
  88491. this.updateGizmoRotationToMatchAttachedMesh = true;
  88492. /**
  88493. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88494. */
  88495. this.updateGizmoPositionToMatchAttachedMesh = true;
  88496. /**
  88497. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88498. */
  88499. this._updateScale = true;
  88500. this._interactionsEnabled = true;
  88501. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88502. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88503. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88504. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88505. _this._rootMesh.scaling.set(dist, dist, dist);
  88506. }
  88507. if (_this.attachedMesh) {
  88508. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88509. if (!_this._rootMesh.rotationQuaternion) {
  88510. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88511. }
  88512. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88513. }
  88514. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88515. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88516. }
  88517. }
  88518. });
  88519. }
  88520. Gizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88521. };
  88522. Object.defineProperty(Gizmo.prototype, "interactionsEnabled", {
  88523. get: function () {
  88524. return this._interactionsEnabled;
  88525. },
  88526. /**
  88527. * If interactions are enabled with this gizmo. (eg. dragging/rotation)
  88528. */
  88529. set: function (value) {
  88530. this._interactionsEnabled = value;
  88531. this._onInteractionsEnabledChanged(value);
  88532. },
  88533. enumerable: true,
  88534. configurable: true
  88535. });
  88536. /**
  88537. * Disposes of the gizmo
  88538. */
  88539. Gizmo.prototype.dispose = function () {
  88540. this._rootMesh.dispose();
  88541. if (this._beforeRenderObserver) {
  88542. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88543. }
  88544. };
  88545. return Gizmo;
  88546. }());
  88547. BABYLON.Gizmo = Gizmo;
  88548. })(BABYLON || (BABYLON = {}));
  88549. //# sourceMappingURL=babylon.gizmo.js.map
  88550. var BABYLON;
  88551. (function (BABYLON) {
  88552. /**
  88553. * Single axis drag gizmo
  88554. */
  88555. var AxisDragGizmo = /** @class */ (function (_super) {
  88556. __extends(AxisDragGizmo, _super);
  88557. /**
  88558. * Creates an AxisDragGizmo
  88559. * @param gizmoLayer The utility layer the gizmo will be added to
  88560. * @param dragAxis The axis which the gizmo will be able to drag on
  88561. * @param color The color of the gizmo
  88562. */
  88563. function AxisDragGizmo(gizmoLayer, dragAxis, color) {
  88564. var _this = _super.call(this, gizmoLayer) || this;
  88565. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88566. // Create Material
  88567. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88568. coloredMaterial.disableLighting = true;
  88569. coloredMaterial.emissiveColor = color;
  88570. // Build mesh on root node
  88571. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88572. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88573. _this._rootMesh.addChild(arrowMesh);
  88574. _this._rootMesh.addChild(arrowTail);
  88575. // Position arrow pointing in its drag axis
  88576. arrowMesh.scaling.scaleInPlace(0.1);
  88577. arrowMesh.material = coloredMaterial;
  88578. arrowMesh.rotation.x = Math.PI / 2;
  88579. arrowMesh.position.z += 0.3;
  88580. arrowTail.rotation.x = Math.PI / 2;
  88581. arrowTail.material = coloredMaterial;
  88582. arrowTail.position.z += 0.2;
  88583. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88584. // Add drag behavior to handle events when the gizmo is dragged
  88585. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88586. _this._dragBehavior.moveAttached = false;
  88587. _this._rootMesh.addBehavior(_this._dragBehavior);
  88588. _this._dragBehavior.onDragObservable.add(function (event) {
  88589. if (!_this.interactionsEnabled) {
  88590. return;
  88591. }
  88592. if (_this.attachedMesh) {
  88593. _this.attachedMesh.position.addInPlace(event.delta);
  88594. }
  88595. });
  88596. return _this;
  88597. }
  88598. AxisDragGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88599. this._dragBehavior.enabled = value;
  88600. };
  88601. /**
  88602. * Disposes of the gizmo
  88603. */
  88604. AxisDragGizmo.prototype.dispose = function () {
  88605. this._dragBehavior.detach();
  88606. _super.prototype.dispose.call(this);
  88607. };
  88608. return AxisDragGizmo;
  88609. }(BABYLON.Gizmo));
  88610. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88611. })(BABYLON || (BABYLON = {}));
  88612. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88613. var BABYLON;
  88614. (function (BABYLON) {
  88615. /**
  88616. * Single axis scale gizmo
  88617. */
  88618. var AxisScaleGizmo = /** @class */ (function (_super) {
  88619. __extends(AxisScaleGizmo, _super);
  88620. /**
  88621. * Creates an AxisScaleGizmo
  88622. * @param gizmoLayer The utility layer the gizmo will be added to
  88623. * @param dragAxis The axis which the gizmo will be able to scale on
  88624. * @param color The color of the gizmo
  88625. */
  88626. function AxisScaleGizmo(gizmoLayer, dragAxis, color) {
  88627. var _this = _super.call(this, gizmoLayer) || this;
  88628. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88629. // Create Material
  88630. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88631. coloredMaterial.disableLighting = true;
  88632. coloredMaterial.emissiveColor = color;
  88633. // Build mesh on root node
  88634. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 1 }, gizmoLayer.utilityLayerScene);
  88635. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.03, height: 0.2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88636. _this._rootMesh.addChild(arrowMesh);
  88637. _this._rootMesh.addChild(arrowTail);
  88638. // Position arrow pointing in its drag axis
  88639. arrowMesh.scaling.scaleInPlace(0.1);
  88640. arrowMesh.material = coloredMaterial;
  88641. arrowMesh.rotation.x = Math.PI / 2;
  88642. arrowMesh.position.z += 0.3;
  88643. arrowTail.rotation.x = Math.PI / 2;
  88644. arrowTail.material = coloredMaterial;
  88645. arrowTail.position.z += 0.2;
  88646. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88647. // Add drag behavior to handle events when the gizmo is dragged
  88648. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: new BABYLON.Vector3(0, 0, 1) });
  88649. _this._dragBehavior.moveAttached = false;
  88650. _this._rootMesh.addBehavior(_this._dragBehavior);
  88651. _this._dragBehavior.onDragObservable.add(function (event) {
  88652. if (!_this.interactionsEnabled) {
  88653. return;
  88654. }
  88655. if (_this.attachedMesh) {
  88656. _this.attachedMesh.scaling.addInPlace(event.delta);
  88657. }
  88658. });
  88659. return _this;
  88660. }
  88661. AxisScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88662. this._dragBehavior.enabled = value;
  88663. };
  88664. /**
  88665. * Disposes of the gizmo
  88666. */
  88667. AxisScaleGizmo.prototype.dispose = function () {
  88668. this._dragBehavior.detach();
  88669. _super.prototype.dispose.call(this);
  88670. };
  88671. return AxisScaleGizmo;
  88672. }(BABYLON.Gizmo));
  88673. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  88674. })(BABYLON || (BABYLON = {}));
  88675. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  88676. var BABYLON;
  88677. (function (BABYLON) {
  88678. /**
  88679. * Single plane rotation gizmo
  88680. */
  88681. var PlaneRotationGizmo = /** @class */ (function (_super) {
  88682. __extends(PlaneRotationGizmo, _super);
  88683. /**
  88684. * Creates a PlaneRotationGizmo
  88685. * @param gizmoLayer The utility layer the gizmo will be added to
  88686. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  88687. * @param color The color of the gizmo
  88688. */
  88689. function PlaneRotationGizmo(gizmoLayer, planeNormal, color) {
  88690. var _this = _super.call(this, gizmoLayer) || this;
  88691. _this.updateGizmoRotationToMatchAttachedMesh = false;
  88692. // Create Material
  88693. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88694. coloredMaterial.disableLighting = true;
  88695. coloredMaterial.emissiveColor = color;
  88696. // Build mesh on root node
  88697. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.3, 20, gizmoLayer.utilityLayerScene, false);
  88698. _this._rootMesh.addChild(rotationMesh);
  88699. // Position arrow pointing in its drag axis
  88700. rotationMesh.scaling.scaleInPlace(0.1);
  88701. rotationMesh.material = coloredMaterial;
  88702. rotationMesh.rotation.x = Math.PI / 2;
  88703. _this._rootMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  88704. // Add drag behavior to handle events when the gizmo is dragged
  88705. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: new BABYLON.Vector3(0, 0, 1) });
  88706. _this._dragBehavior.moveAttached = false;
  88707. _this._rootMesh.addBehavior(_this._dragBehavior);
  88708. var lastDragPosition = null;
  88709. _this._dragBehavior.onDragStartObservable.add(function (e) {
  88710. if (!_this.interactionsEnabled) {
  88711. return;
  88712. }
  88713. lastDragPosition = e.dragPlanePoint;
  88714. });
  88715. _this._dragBehavior.onDragObservable.add(function (event) {
  88716. if (!_this.interactionsEnabled) {
  88717. return;
  88718. }
  88719. if (_this.attachedMesh && lastDragPosition) {
  88720. if (!_this.attachedMesh.rotationQuaternion) {
  88721. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  88722. }
  88723. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  88724. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  88725. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  88726. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  88727. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  88728. var angle = Math.atan2(cross.length(), dot);
  88729. var up = planeNormal.clone();
  88730. // Flip up vector depending on which side the camera is on
  88731. if (gizmoLayer.utilityLayerScene.activeCamera) {
  88732. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  88733. if (BABYLON.Vector3.Dot(camVec, up) > 0) {
  88734. up.scaleInPlace(-1);
  88735. }
  88736. }
  88737. var halfCircleSide = BABYLON.Vector3.Dot(up, cross) > 0.0;
  88738. if (halfCircleSide)
  88739. angle = -angle;
  88740. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  88741. var quaternionCoefficient = Math.sin(angle / 2);
  88742. var amountToRotate = new BABYLON.Quaternion(up.x * quaternionCoefficient, up.y * quaternionCoefficient, up.z * quaternionCoefficient, Math.cos(angle / 2));
  88743. // Rotate selected mesh quaternion over fixed axis
  88744. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  88745. lastDragPosition = event.dragPlanePoint;
  88746. }
  88747. });
  88748. return _this;
  88749. }
  88750. PlaneRotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88751. this._dragBehavior.enabled = value;
  88752. };
  88753. /**
  88754. * Disposes of the gizmo
  88755. */
  88756. PlaneRotationGizmo.prototype.dispose = function () {
  88757. this._dragBehavior.detach();
  88758. _super.prototype.dispose.call(this);
  88759. };
  88760. return PlaneRotationGizmo;
  88761. }(BABYLON.Gizmo));
  88762. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  88763. })(BABYLON || (BABYLON = {}));
  88764. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  88765. var BABYLON;
  88766. (function (BABYLON) {
  88767. /**
  88768. * Gizmo that enables dragging a mesh along 3 axis
  88769. */
  88770. var PositionGizmo = /** @class */ (function (_super) {
  88771. __extends(PositionGizmo, _super);
  88772. /**
  88773. * Creates a PositionGizmo
  88774. * @param gizmoLayer The utility layer the gizmo will be added to
  88775. */
  88776. function PositionGizmo(gizmoLayer) {
  88777. var _this = _super.call(this, gizmoLayer) || this;
  88778. _this._xDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88779. _this._yDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88780. _this._zDrag = new BABYLON.AxisDragGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88781. return _this;
  88782. }
  88783. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  88784. set: function (mesh) {
  88785. this._xDrag.attachedMesh = mesh;
  88786. this._yDrag.attachedMesh = mesh;
  88787. this._zDrag.attachedMesh = mesh;
  88788. },
  88789. enumerable: true,
  88790. configurable: true
  88791. });
  88792. PositionGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88793. this._xDrag.interactionsEnabled = value;
  88794. this._yDrag.interactionsEnabled = value;
  88795. this._zDrag.interactionsEnabled = value;
  88796. };
  88797. /**
  88798. * Disposes of the gizmo
  88799. */
  88800. PositionGizmo.prototype.dispose = function () {
  88801. this._xDrag.dispose();
  88802. this._yDrag.dispose();
  88803. this._zDrag.dispose();
  88804. };
  88805. return PositionGizmo;
  88806. }(BABYLON.Gizmo));
  88807. BABYLON.PositionGizmo = PositionGizmo;
  88808. })(BABYLON || (BABYLON = {}));
  88809. //# sourceMappingURL=babylon.positionGizmo.js.map
  88810. var BABYLON;
  88811. (function (BABYLON) {
  88812. /**
  88813. * Gizmo that enables rotating a mesh along 3 axis
  88814. */
  88815. var RotationGizmo = /** @class */ (function (_super) {
  88816. __extends(RotationGizmo, _super);
  88817. /**
  88818. * Creates a RotationGizmo
  88819. * @param gizmoLayer The utility layer the gizmo will be added to
  88820. */
  88821. function RotationGizmo(gizmoLayer) {
  88822. var _this = _super.call(this, gizmoLayer) || this;
  88823. _this._xDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88824. _this._yDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88825. _this._zDrag = new BABYLON.PlaneRotationGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88826. return _this;
  88827. }
  88828. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  88829. set: function (mesh) {
  88830. this._xDrag.attachedMesh = mesh;
  88831. this._yDrag.attachedMesh = mesh;
  88832. this._zDrag.attachedMesh = mesh;
  88833. },
  88834. enumerable: true,
  88835. configurable: true
  88836. });
  88837. RotationGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88838. this._xDrag.interactionsEnabled = value;
  88839. this._yDrag.interactionsEnabled = value;
  88840. this._zDrag.interactionsEnabled = value;
  88841. };
  88842. /**
  88843. * Disposes of the gizmo
  88844. */
  88845. RotationGizmo.prototype.dispose = function () {
  88846. this._xDrag.dispose();
  88847. this._yDrag.dispose();
  88848. this._zDrag.dispose();
  88849. };
  88850. return RotationGizmo;
  88851. }(BABYLON.Gizmo));
  88852. BABYLON.RotationGizmo = RotationGizmo;
  88853. })(BABYLON || (BABYLON = {}));
  88854. //# sourceMappingURL=babylon.rotationGizmo.js.map
  88855. var BABYLON;
  88856. (function (BABYLON) {
  88857. /**
  88858. * Gizmo that enables scaling a mesh along 3 axis
  88859. */
  88860. var ScaleGizmo = /** @class */ (function (_super) {
  88861. __extends(ScaleGizmo, _super);
  88862. /**
  88863. * Creates a ScaleGizmo
  88864. * @param gizmoLayer The utility layer the gizmo will be added to
  88865. */
  88866. function ScaleGizmo(gizmoLayer) {
  88867. var _this = _super.call(this, gizmoLayer) || this;
  88868. _this._xDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.FromHexString("#00b894"));
  88869. _this._yDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.FromHexString("#d63031"));
  88870. _this._zDrag = new BABYLON.AxisScaleGizmo(gizmoLayer, new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.FromHexString("#0984e3"));
  88871. return _this;
  88872. }
  88873. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  88874. set: function (mesh) {
  88875. this._xDrag.attachedMesh = mesh;
  88876. this._yDrag.attachedMesh = mesh;
  88877. this._zDrag.attachedMesh = mesh;
  88878. },
  88879. enumerable: true,
  88880. configurable: true
  88881. });
  88882. ScaleGizmo.prototype._onInteractionsEnabledChanged = function (value) {
  88883. this._xDrag.interactionsEnabled = value;
  88884. this._yDrag.interactionsEnabled = value;
  88885. this._zDrag.interactionsEnabled = value;
  88886. };
  88887. /**
  88888. * Disposes of the gizmo
  88889. */
  88890. ScaleGizmo.prototype.dispose = function () {
  88891. this._xDrag.dispose();
  88892. this._yDrag.dispose();
  88893. this._zDrag.dispose();
  88894. };
  88895. return ScaleGizmo;
  88896. }(BABYLON.Gizmo));
  88897. BABYLON.ScaleGizmo = ScaleGizmo;
  88898. })(BABYLON || (BABYLON = {}));
  88899. //# sourceMappingURL=babylon.scaleGizmo.js.map
  88900. var BABYLON;
  88901. (function (BABYLON) {
  88902. /**
  88903. * Bounding box gizmo
  88904. */
  88905. var BoundingBoxGizmo = /** @class */ (function (_super) {
  88906. __extends(BoundingBoxGizmo, _super);
  88907. /**
  88908. * Creates an BoundingBoxGizmo
  88909. * @param gizmoLayer The utility layer the gizmo will be added to
  88910. * @param color The color of the gizmo
  88911. */
  88912. function BoundingBoxGizmo(gizmoLayer, color) {
  88913. var _this = _super.call(this, gizmoLayer) || this;
  88914. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  88915. _this._renderObserver = null;
  88916. _this._pointerObserver = null;
  88917. _this._scaleDragSpeed = 0.2;
  88918. _this._tmpQuaternion = new BABYLON.Quaternion();
  88919. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88920. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  88921. _this._updateScale = false;
  88922. // Create Materials
  88923. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88924. coloredMaterial.disableLighting = true;
  88925. coloredMaterial.emissiveColor = color;
  88926. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88927. hoverColoredMaterial.disableLighting = true;
  88928. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88929. // Build bounding box out of lines
  88930. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88931. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  88932. var lines = [];
  88933. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  88934. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  88935. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  88936. 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));
  88937. 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));
  88938. 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));
  88939. 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));
  88940. 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));
  88941. 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));
  88942. 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));
  88943. 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));
  88944. 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));
  88945. lines.forEach(function (l) {
  88946. l.color = color;
  88947. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  88948. l.isPickable = false;
  88949. _this._lineBoundingBox.addChild(l);
  88950. });
  88951. _this._rootMesh.addChild(_this._lineBoundingBox);
  88952. // Create rotation spheres
  88953. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88954. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  88955. var _loop_1 = function (i_1) {
  88956. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 0.1 }, gizmoLayer.utilityLayerScene);
  88957. sphere.rotationQuaternion = new BABYLON.Quaternion();
  88958. sphere.material = coloredMaterial;
  88959. // Drag behavior
  88960. _dragBehavior = new BABYLON.PointerDragBehavior({});
  88961. _dragBehavior.moveAttached = false;
  88962. _dragBehavior.updateDragPlane = false;
  88963. sphere.addBehavior(_dragBehavior);
  88964. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  88965. var totalTurnAmountOfDrag = 0;
  88966. _dragBehavior.onDragStartObservable.add(function (event) {
  88967. startingTurnDirection.copyFrom(sphere.forward);
  88968. totalTurnAmountOfDrag = 0;
  88969. });
  88970. _dragBehavior.onDragObservable.add(function (event) {
  88971. if (_this.attachedMesh) {
  88972. var worldDragDirection = startingTurnDirection;
  88973. // Project the world right on to the drag plane
  88974. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  88975. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  88976. // project drag delta on to the resulting drag axis and rotate based on that
  88977. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  88978. // Rotate based on axis
  88979. if (!_this.attachedMesh.rotationQuaternion) {
  88980. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  88981. }
  88982. // Do not allow the object to turn more than a full circle
  88983. totalTurnAmountOfDrag += projectDist;
  88984. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  88985. if (i_1 >= 8) {
  88986. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  88987. }
  88988. else if (i_1 >= 4) {
  88989. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  88990. }
  88991. else {
  88992. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  88993. }
  88994. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  88995. }
  88996. }
  88997. });
  88998. // Selection/deselection
  88999. _dragBehavior.onDragStartObservable.add(function () {
  89000. _this._selectNode(sphere);
  89001. });
  89002. _dragBehavior.onDragEndObservable.add(function () {
  89003. _this._selectNode(null);
  89004. });
  89005. this_1._rotateSpheresParent.addChild(sphere);
  89006. };
  89007. var this_1 = this, _dragBehavior;
  89008. for (var i_1 = 0; i_1 < 12; i_1++) {
  89009. _loop_1(i_1);
  89010. }
  89011. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89012. // Create scale cubes
  89013. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89014. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89015. for (var i = 0; i < 2; i++) {
  89016. for (var j = 0; j < 2; j++) {
  89017. var _loop_2 = function () {
  89018. var box = BABYLON.MeshBuilder.CreateBox("", { size: 0.1 }, gizmoLayer.utilityLayerScene);
  89019. box.material = coloredMaterial;
  89020. // Dragging logic
  89021. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89022. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89023. _dragBehavior.moveAttached = false;
  89024. box.addBehavior(_dragBehavior);
  89025. _dragBehavior.onDragObservable.add(function (event) {
  89026. if (_this.attachedMesh) {
  89027. // Current boudning box dimensions
  89028. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89029. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89030. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89031. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89032. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89033. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89034. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89035. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89036. // Update scale and position
  89037. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89038. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89039. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89040. }
  89041. });
  89042. // Selection/deselection
  89043. _dragBehavior.onDragStartObservable.add(function () {
  89044. _this._selectNode(box);
  89045. });
  89046. _dragBehavior.onDragEndObservable.add(function () {
  89047. _this._selectNode(null);
  89048. });
  89049. this_2._scaleBoxesParent.addChild(box);
  89050. };
  89051. var this_2 = this, _dragBehavior;
  89052. for (var k = 0; k < 2; k++) {
  89053. _loop_2();
  89054. }
  89055. }
  89056. }
  89057. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89058. // Hover color change
  89059. var pointerIds = new Array();
  89060. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89061. if (!pointerIds[pointerInfo.event.pointerId]) {
  89062. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89063. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89064. pointerIds[pointerInfo.event.pointerId] = mesh;
  89065. mesh.material = hoverColoredMaterial;
  89066. }
  89067. });
  89068. }
  89069. else {
  89070. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89071. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89072. delete pointerIds[pointerInfo.event.pointerId];
  89073. }
  89074. }
  89075. });
  89076. // Update bounding box positions
  89077. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89078. _this._updateBoundingBox();
  89079. });
  89080. _this._updateBoundingBox();
  89081. return _this;
  89082. }
  89083. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89084. this._rotateSpheresParent.getChildMeshes()
  89085. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89086. m.isVisible = (!selectedMesh || m == selectedMesh);
  89087. });
  89088. };
  89089. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89090. if (this.attachedMesh) {
  89091. // Update bounding dimensions/positions
  89092. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89093. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89094. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89095. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89096. }
  89097. // Update rotation sphere locations
  89098. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89099. for (var i = 0; i < 3; i++) {
  89100. for (var j = 0; j < 2; j++) {
  89101. for (var k = 0; k < 2; k++) {
  89102. var index = ((i * 4) + (j * 2)) + k;
  89103. if (i == 0) {
  89104. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89105. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89106. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89107. }
  89108. if (i == 1) {
  89109. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89110. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89111. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89112. }
  89113. if (i == 2) {
  89114. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89115. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89116. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89117. }
  89118. }
  89119. }
  89120. }
  89121. // Update scale box locations
  89122. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89123. for (var i = 0; i < 2; i++) {
  89124. for (var j = 0; j < 2; j++) {
  89125. for (var k = 0; k < 2; k++) {
  89126. var index = ((i * 4) + (j * 2)) + k;
  89127. if (scaleBoxes[index]) {
  89128. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89129. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89130. }
  89131. }
  89132. }
  89133. }
  89134. };
  89135. /**
  89136. * Disposes of the gizmo
  89137. */
  89138. BoundingBoxGizmo.prototype.dispose = function () {
  89139. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89140. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89141. this._lineBoundingBox.dispose();
  89142. this._rotateSpheresParent.dispose();
  89143. this._scaleBoxesParent.dispose();
  89144. _super.prototype.dispose.call(this);
  89145. };
  89146. return BoundingBoxGizmo;
  89147. }(BABYLON.Gizmo));
  89148. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89149. })(BABYLON || (BABYLON = {}));
  89150. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89151. var BABYLON;
  89152. (function (BABYLON) {
  89153. /**
  89154. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89155. */
  89156. var GizmoManager = /** @class */ (function () {
  89157. /**
  89158. * Instatiates a gizmo manager
  89159. * @param scene the scene to overlay the gizmos on top of
  89160. * @param options If only a single gizmo should exist at one time
  89161. */
  89162. function GizmoManager(scene, options) {
  89163. var _this = this;
  89164. this.scene = scene;
  89165. // Set of gizmos that are currently in the scene for each mesh
  89166. this._gizmoSet = {};
  89167. this._pointerObserver = null;
  89168. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89169. // Options parsing
  89170. if (!options) {
  89171. options = {};
  89172. }
  89173. if (options.singleGizmo === undefined) {
  89174. options.singleGizmo = true;
  89175. }
  89176. // Instatiate/dispose gizmos based on pointer actions
  89177. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89178. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89179. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89180. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89181. if (options.singleGizmo) {
  89182. _this._clearGizmos();
  89183. }
  89184. // Enable gizmo when mesh is selected
  89185. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89186. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89187. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89188. }
  89189. else {
  89190. if (!options.singleGizmo) {
  89191. // Disable gizmo when clicked again
  89192. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89193. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89194. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89195. }
  89196. }
  89197. }
  89198. else {
  89199. if (options.singleGizmo) {
  89200. // Disable gizmo when clicked away
  89201. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89202. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89203. if (gizmoPick && !gizmoPick.hit) {
  89204. _this._clearGizmos();
  89205. }
  89206. }
  89207. }
  89208. }
  89209. }
  89210. });
  89211. }
  89212. /**
  89213. * Disposes of the gizmo manager
  89214. */
  89215. GizmoManager.prototype.dispose = function () {
  89216. this.scene.onPointerObservable.remove(this._pointerObserver);
  89217. this._clearGizmos();
  89218. this._gizmoLayer.dispose();
  89219. };
  89220. GizmoManager.prototype._clearGizmos = function () {
  89221. for (var key in this._gizmoSet) {
  89222. if (this._gizmoSet.hasOwnProperty(key)) {
  89223. this._gizmoSet[key].positionGizmo.dispose();
  89224. this._gizmoSet[key].rotationGizmo.dispose();
  89225. delete this._gizmoSet[key];
  89226. }
  89227. }
  89228. };
  89229. return GizmoManager;
  89230. }());
  89231. BABYLON.GizmoManager = GizmoManager;
  89232. })(BABYLON || (BABYLON = {}));
  89233. //# sourceMappingURL=babylon.gizmoManager.js.map
  89234. var BABYLON;
  89235. (function (BABYLON) {
  89236. /**
  89237. * Defines a target to use with MorphTargetManager
  89238. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89239. */
  89240. var MorphTarget = /** @class */ (function () {
  89241. /**
  89242. * Creates a new MorphTarget
  89243. * @param name defines the name of the target
  89244. * @param influence defines the influence to use
  89245. */
  89246. function MorphTarget(
  89247. /** defines the name of the target */
  89248. name, influence, scene) {
  89249. if (influence === void 0) { influence = 0; }
  89250. if (scene === void 0) { scene = null; }
  89251. this.name = name;
  89252. /**
  89253. * Gets or sets the list of animations
  89254. */
  89255. this.animations = new Array();
  89256. this._positions = null;
  89257. this._normals = null;
  89258. this._tangents = null;
  89259. /**
  89260. * Observable raised when the influence changes
  89261. */
  89262. this.onInfluenceChanged = new BABYLON.Observable();
  89263. this._animationPropertiesOverride = null;
  89264. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89265. this.influence = influence;
  89266. }
  89267. Object.defineProperty(MorphTarget.prototype, "influence", {
  89268. /**
  89269. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89270. */
  89271. get: function () {
  89272. return this._influence;
  89273. },
  89274. set: function (influence) {
  89275. if (this._influence === influence) {
  89276. return;
  89277. }
  89278. var previous = this._influence;
  89279. this._influence = influence;
  89280. if (this.onInfluenceChanged.hasObservers) {
  89281. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89282. }
  89283. },
  89284. enumerable: true,
  89285. configurable: true
  89286. });
  89287. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89288. /**
  89289. * Gets or sets the animation properties override
  89290. */
  89291. get: function () {
  89292. if (!this._animationPropertiesOverride && this._scene) {
  89293. return this._scene.animationPropertiesOverride;
  89294. }
  89295. return this._animationPropertiesOverride;
  89296. },
  89297. set: function (value) {
  89298. this._animationPropertiesOverride = value;
  89299. },
  89300. enumerable: true,
  89301. configurable: true
  89302. });
  89303. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89304. /**
  89305. * Gets a boolean defining if the target contains position data
  89306. */
  89307. get: function () {
  89308. return !!this._positions;
  89309. },
  89310. enumerable: true,
  89311. configurable: true
  89312. });
  89313. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89314. /**
  89315. * Gets a boolean defining if the target contains normal data
  89316. */
  89317. get: function () {
  89318. return !!this._normals;
  89319. },
  89320. enumerable: true,
  89321. configurable: true
  89322. });
  89323. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89324. /**
  89325. * Gets a boolean defining if the target contains tangent data
  89326. */
  89327. get: function () {
  89328. return !!this._tangents;
  89329. },
  89330. enumerable: true,
  89331. configurable: true
  89332. });
  89333. /**
  89334. * Affects position data to this target
  89335. * @param data defines the position data to use
  89336. */
  89337. MorphTarget.prototype.setPositions = function (data) {
  89338. this._positions = data;
  89339. };
  89340. /**
  89341. * Gets the position data stored in this target
  89342. * @returns a FloatArray containing the position data (or null if not present)
  89343. */
  89344. MorphTarget.prototype.getPositions = function () {
  89345. return this._positions;
  89346. };
  89347. /**
  89348. * Affects normal data to this target
  89349. * @param data defines the normal data to use
  89350. */
  89351. MorphTarget.prototype.setNormals = function (data) {
  89352. this._normals = data;
  89353. };
  89354. /**
  89355. * Gets the normal data stored in this target
  89356. * @returns a FloatArray containing the normal data (or null if not present)
  89357. */
  89358. MorphTarget.prototype.getNormals = function () {
  89359. return this._normals;
  89360. };
  89361. /**
  89362. * Affects tangent data to this target
  89363. * @param data defines the tangent data to use
  89364. */
  89365. MorphTarget.prototype.setTangents = function (data) {
  89366. this._tangents = data;
  89367. };
  89368. /**
  89369. * Gets the tangent data stored in this target
  89370. * @returns a FloatArray containing the tangent data (or null if not present)
  89371. */
  89372. MorphTarget.prototype.getTangents = function () {
  89373. return this._tangents;
  89374. };
  89375. /**
  89376. * Serializes the current target into a Serialization object
  89377. * @returns the serialized object
  89378. */
  89379. MorphTarget.prototype.serialize = function () {
  89380. var serializationObject = {};
  89381. serializationObject.name = this.name;
  89382. serializationObject.influence = this.influence;
  89383. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89384. if (this.hasNormals) {
  89385. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89386. }
  89387. if (this.hasTangents) {
  89388. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  89389. }
  89390. // Animations
  89391. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  89392. return serializationObject;
  89393. };
  89394. // Statics
  89395. /**
  89396. * Creates a new target from serialized data
  89397. * @param serializationObject defines the serialized data to use
  89398. * @returns a new MorphTarget
  89399. */
  89400. MorphTarget.Parse = function (serializationObject) {
  89401. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  89402. result.setPositions(serializationObject.positions);
  89403. if (serializationObject.normals) {
  89404. result.setNormals(serializationObject.normals);
  89405. }
  89406. if (serializationObject.tangents) {
  89407. result.setTangents(serializationObject.tangents);
  89408. }
  89409. // Animations
  89410. if (serializationObject.animations) {
  89411. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  89412. var parsedAnimation = serializationObject.animations[animationIndex];
  89413. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  89414. }
  89415. }
  89416. return result;
  89417. };
  89418. /**
  89419. * Creates a MorphTarget from mesh data
  89420. * @param mesh defines the source mesh
  89421. * @param name defines the name to use for the new target
  89422. * @param influence defines the influence to attach to the target
  89423. * @returns a new MorphTarget
  89424. */
  89425. MorphTarget.FromMesh = function (mesh, name, influence) {
  89426. if (!name) {
  89427. name = mesh.name;
  89428. }
  89429. var result = new MorphTarget(name, influence, mesh.getScene());
  89430. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  89431. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  89432. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  89433. }
  89434. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  89435. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  89436. }
  89437. return result;
  89438. };
  89439. return MorphTarget;
  89440. }());
  89441. BABYLON.MorphTarget = MorphTarget;
  89442. })(BABYLON || (BABYLON = {}));
  89443. //# sourceMappingURL=babylon.morphTarget.js.map
  89444. var BABYLON;
  89445. (function (BABYLON) {
  89446. /**
  89447. * This class is used to deform meshes using morphing between different targets
  89448. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89449. */
  89450. var MorphTargetManager = /** @class */ (function () {
  89451. /**
  89452. * Creates a new MorphTargetManager
  89453. * @param scene defines the current scene
  89454. */
  89455. function MorphTargetManager(scene) {
  89456. if (scene === void 0) { scene = null; }
  89457. this._targets = new Array();
  89458. this._targetObservable = new Array();
  89459. this._activeTargets = new BABYLON.SmartArray(16);
  89460. this._supportsNormals = false;
  89461. this._supportsTangents = false;
  89462. this._vertexCount = 0;
  89463. this._uniqueId = 0;
  89464. this._tempInfluences = new Array();
  89465. if (!scene) {
  89466. scene = BABYLON.Engine.LastCreatedScene;
  89467. }
  89468. this._scene = scene;
  89469. if (this._scene) {
  89470. this._scene.morphTargetManagers.push(this);
  89471. this._uniqueId = this._scene.getUniqueId();
  89472. }
  89473. }
  89474. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  89475. /**
  89476. * Gets the unique ID of this manager
  89477. */
  89478. get: function () {
  89479. return this._uniqueId;
  89480. },
  89481. enumerable: true,
  89482. configurable: true
  89483. });
  89484. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  89485. /**
  89486. * Gets the number of vertices handled by this manager
  89487. */
  89488. get: function () {
  89489. return this._vertexCount;
  89490. },
  89491. enumerable: true,
  89492. configurable: true
  89493. });
  89494. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  89495. /**
  89496. * Gets a boolean indicating if this manager supports morphing of normals
  89497. */
  89498. get: function () {
  89499. return this._supportsNormals;
  89500. },
  89501. enumerable: true,
  89502. configurable: true
  89503. });
  89504. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  89505. /**
  89506. * Gets a boolean indicating if this manager supports morphing of tangents
  89507. */
  89508. get: function () {
  89509. return this._supportsTangents;
  89510. },
  89511. enumerable: true,
  89512. configurable: true
  89513. });
  89514. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  89515. /**
  89516. * Gets the number of targets stored in this manager
  89517. */
  89518. get: function () {
  89519. return this._targets.length;
  89520. },
  89521. enumerable: true,
  89522. configurable: true
  89523. });
  89524. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  89525. /**
  89526. * Gets the number of influencers (ie. the number of targets with influences > 0)
  89527. */
  89528. get: function () {
  89529. return this._activeTargets.length;
  89530. },
  89531. enumerable: true,
  89532. configurable: true
  89533. });
  89534. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  89535. /**
  89536. * Gets the list of influences (one per target)
  89537. */
  89538. get: function () {
  89539. return this._influences;
  89540. },
  89541. enumerable: true,
  89542. configurable: true
  89543. });
  89544. /**
  89545. * Gets the active target at specified index. An active target is a target with an influence > 0
  89546. * @param index defines the index to check
  89547. * @returns the requested target
  89548. */
  89549. MorphTargetManager.prototype.getActiveTarget = function (index) {
  89550. return this._activeTargets.data[index];
  89551. };
  89552. /**
  89553. * Gets the target at specified index
  89554. * @param index defines the index to check
  89555. * @returns the requested target
  89556. */
  89557. MorphTargetManager.prototype.getTarget = function (index) {
  89558. return this._targets[index];
  89559. };
  89560. /**
  89561. * Add a new target to this manager
  89562. * @param target defines the target to add
  89563. */
  89564. MorphTargetManager.prototype.addTarget = function (target) {
  89565. var _this = this;
  89566. this._targets.push(target);
  89567. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  89568. _this._syncActiveTargets(needUpdate);
  89569. }));
  89570. this._syncActiveTargets(true);
  89571. };
  89572. /**
  89573. * Removes a target from the manager
  89574. * @param target defines the target to remove
  89575. */
  89576. MorphTargetManager.prototype.removeTarget = function (target) {
  89577. var index = this._targets.indexOf(target);
  89578. if (index >= 0) {
  89579. this._targets.splice(index, 1);
  89580. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  89581. this._syncActiveTargets(true);
  89582. }
  89583. };
  89584. /**
  89585. * Serializes the current manager into a Serialization object
  89586. * @returns the serialized object
  89587. */
  89588. MorphTargetManager.prototype.serialize = function () {
  89589. var serializationObject = {};
  89590. serializationObject.id = this.uniqueId;
  89591. serializationObject.targets = [];
  89592. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89593. var target = _a[_i];
  89594. serializationObject.targets.push(target.serialize());
  89595. }
  89596. return serializationObject;
  89597. };
  89598. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  89599. var influenceCount = 0;
  89600. this._activeTargets.reset();
  89601. this._supportsNormals = true;
  89602. this._supportsTangents = true;
  89603. this._vertexCount = 0;
  89604. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  89605. var target = _a[_i];
  89606. this._activeTargets.push(target);
  89607. this._tempInfluences[influenceCount++] = target.influence;
  89608. var positions = target.getPositions();
  89609. if (positions) {
  89610. this._supportsNormals = this._supportsNormals && target.hasNormals;
  89611. this._supportsTangents = this._supportsTangents && target.hasTangents;
  89612. var vertexCount = positions.length / 3;
  89613. if (this._vertexCount === 0) {
  89614. this._vertexCount = vertexCount;
  89615. }
  89616. else if (this._vertexCount !== vertexCount) {
  89617. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  89618. return;
  89619. }
  89620. }
  89621. }
  89622. if (!this._influences || this._influences.length !== influenceCount) {
  89623. this._influences = new Float32Array(influenceCount);
  89624. }
  89625. for (var index = 0; index < influenceCount; index++) {
  89626. this._influences[index] = this._tempInfluences[index];
  89627. }
  89628. if (needUpdate) {
  89629. this.synchronize();
  89630. }
  89631. };
  89632. /**
  89633. * Syncrhonize the targets with all the meshes using this morph target manager
  89634. */
  89635. MorphTargetManager.prototype.synchronize = function () {
  89636. if (!this._scene) {
  89637. return;
  89638. }
  89639. // Flag meshes as dirty to resync with the active targets
  89640. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  89641. var mesh = _a[_i];
  89642. if (mesh.morphTargetManager === this) {
  89643. mesh._syncGeometryWithMorphTargetManager();
  89644. }
  89645. }
  89646. };
  89647. // Statics
  89648. /**
  89649. * Creates a new MorphTargetManager from serialized data
  89650. * @param serializationObject defines the serialized data
  89651. * @param scene defines the hosting scene
  89652. * @returns the new MorphTargetManager
  89653. */
  89654. MorphTargetManager.Parse = function (serializationObject, scene) {
  89655. var result = new MorphTargetManager(scene);
  89656. result._uniqueId = serializationObject.id;
  89657. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  89658. var targetData = _a[_i];
  89659. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  89660. }
  89661. return result;
  89662. };
  89663. return MorphTargetManager;
  89664. }());
  89665. BABYLON.MorphTargetManager = MorphTargetManager;
  89666. })(BABYLON || (BABYLON = {}));
  89667. //# sourceMappingURL=babylon.morphTargetManager.js.map
  89668. var BABYLON;
  89669. (function (BABYLON) {
  89670. var Octree = /** @class */ (function () {
  89671. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  89672. if (maxDepth === void 0) { maxDepth = 2; }
  89673. this.maxDepth = maxDepth;
  89674. this.dynamicContent = new Array();
  89675. this._maxBlockCapacity = maxBlockCapacity || 64;
  89676. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  89677. this._creationFunc = creationFunc;
  89678. }
  89679. // Methods
  89680. Octree.prototype.update = function (worldMin, worldMax, entries) {
  89681. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  89682. };
  89683. Octree.prototype.addMesh = function (entry) {
  89684. for (var index = 0; index < this.blocks.length; index++) {
  89685. var block = this.blocks[index];
  89686. block.addEntry(entry);
  89687. }
  89688. };
  89689. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  89690. this._selectionContent.reset();
  89691. for (var index = 0; index < this.blocks.length; index++) {
  89692. var block = this.blocks[index];
  89693. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  89694. }
  89695. if (allowDuplicate) {
  89696. this._selectionContent.concat(this.dynamicContent);
  89697. }
  89698. else {
  89699. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89700. }
  89701. return this._selectionContent;
  89702. };
  89703. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  89704. this._selectionContent.reset();
  89705. for (var index = 0; index < this.blocks.length; index++) {
  89706. var block = this.blocks[index];
  89707. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  89708. }
  89709. if (allowDuplicate) {
  89710. this._selectionContent.concat(this.dynamicContent);
  89711. }
  89712. else {
  89713. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89714. }
  89715. return this._selectionContent;
  89716. };
  89717. Octree.prototype.intersectsRay = function (ray) {
  89718. this._selectionContent.reset();
  89719. for (var index = 0; index < this.blocks.length; index++) {
  89720. var block = this.blocks[index];
  89721. block.intersectsRay(ray, this._selectionContent);
  89722. }
  89723. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  89724. return this._selectionContent;
  89725. };
  89726. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  89727. target.blocks = new Array();
  89728. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  89729. // Segmenting space
  89730. for (var x = 0; x < 2; x++) {
  89731. for (var y = 0; y < 2; y++) {
  89732. for (var z = 0; z < 2; z++) {
  89733. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  89734. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  89735. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  89736. block.addEntries(entries);
  89737. target.blocks.push(block);
  89738. }
  89739. }
  89740. }
  89741. };
  89742. Octree.CreationFuncForMeshes = function (entry, block) {
  89743. var boundingInfo = entry.getBoundingInfo();
  89744. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89745. block.entries.push(entry);
  89746. }
  89747. };
  89748. Octree.CreationFuncForSubMeshes = function (entry, block) {
  89749. var boundingInfo = entry.getBoundingInfo();
  89750. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  89751. block.entries.push(entry);
  89752. }
  89753. };
  89754. return Octree;
  89755. }());
  89756. BABYLON.Octree = Octree;
  89757. })(BABYLON || (BABYLON = {}));
  89758. //# sourceMappingURL=babylon.octree.js.map
  89759. var BABYLON;
  89760. (function (BABYLON) {
  89761. var OctreeBlock = /** @class */ (function () {
  89762. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  89763. this.entries = new Array();
  89764. this._boundingVectors = new Array();
  89765. this._capacity = capacity;
  89766. this._depth = depth;
  89767. this._maxDepth = maxDepth;
  89768. this._creationFunc = creationFunc;
  89769. this._minPoint = minPoint;
  89770. this._maxPoint = maxPoint;
  89771. this._boundingVectors.push(minPoint.clone());
  89772. this._boundingVectors.push(maxPoint.clone());
  89773. this._boundingVectors.push(minPoint.clone());
  89774. this._boundingVectors[2].x = maxPoint.x;
  89775. this._boundingVectors.push(minPoint.clone());
  89776. this._boundingVectors[3].y = maxPoint.y;
  89777. this._boundingVectors.push(minPoint.clone());
  89778. this._boundingVectors[4].z = maxPoint.z;
  89779. this._boundingVectors.push(maxPoint.clone());
  89780. this._boundingVectors[5].z = minPoint.z;
  89781. this._boundingVectors.push(maxPoint.clone());
  89782. this._boundingVectors[6].x = minPoint.x;
  89783. this._boundingVectors.push(maxPoint.clone());
  89784. this._boundingVectors[7].y = minPoint.y;
  89785. }
  89786. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  89787. // Property
  89788. get: function () {
  89789. return this._capacity;
  89790. },
  89791. enumerable: true,
  89792. configurable: true
  89793. });
  89794. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  89795. get: function () {
  89796. return this._minPoint;
  89797. },
  89798. enumerable: true,
  89799. configurable: true
  89800. });
  89801. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  89802. get: function () {
  89803. return this._maxPoint;
  89804. },
  89805. enumerable: true,
  89806. configurable: true
  89807. });
  89808. // Methods
  89809. OctreeBlock.prototype.addEntry = function (entry) {
  89810. if (this.blocks) {
  89811. for (var index = 0; index < this.blocks.length; index++) {
  89812. var block = this.blocks[index];
  89813. block.addEntry(entry);
  89814. }
  89815. return;
  89816. }
  89817. this._creationFunc(entry, this);
  89818. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  89819. this.createInnerBlocks();
  89820. }
  89821. };
  89822. OctreeBlock.prototype.addEntries = function (entries) {
  89823. for (var index = 0; index < entries.length; index++) {
  89824. var mesh = entries[index];
  89825. this.addEntry(mesh);
  89826. }
  89827. };
  89828. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  89829. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  89830. if (this.blocks) {
  89831. for (var index = 0; index < this.blocks.length; index++) {
  89832. var block = this.blocks[index];
  89833. block.select(frustumPlanes, selection, allowDuplicate);
  89834. }
  89835. return;
  89836. }
  89837. if (allowDuplicate) {
  89838. selection.concat(this.entries);
  89839. }
  89840. else {
  89841. selection.concatWithNoDuplicate(this.entries);
  89842. }
  89843. }
  89844. };
  89845. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  89846. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  89847. if (this.blocks) {
  89848. for (var index = 0; index < this.blocks.length; index++) {
  89849. var block = this.blocks[index];
  89850. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  89851. }
  89852. return;
  89853. }
  89854. if (allowDuplicate) {
  89855. selection.concat(this.entries);
  89856. }
  89857. else {
  89858. selection.concatWithNoDuplicate(this.entries);
  89859. }
  89860. }
  89861. };
  89862. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  89863. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  89864. if (this.blocks) {
  89865. for (var index = 0; index < this.blocks.length; index++) {
  89866. var block = this.blocks[index];
  89867. block.intersectsRay(ray, selection);
  89868. }
  89869. return;
  89870. }
  89871. selection.concatWithNoDuplicate(this.entries);
  89872. }
  89873. };
  89874. OctreeBlock.prototype.createInnerBlocks = function () {
  89875. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  89876. };
  89877. return OctreeBlock;
  89878. }());
  89879. BABYLON.OctreeBlock = OctreeBlock;
  89880. })(BABYLON || (BABYLON = {}));
  89881. //# sourceMappingURL=babylon.octreeBlock.js.map
  89882. var BABYLON;
  89883. (function (BABYLON) {
  89884. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  89885. __extends(VRDistortionCorrectionPostProcess, _super);
  89886. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  89887. var _this = _super.call(this, name, "vrDistortionCorrection", [
  89888. 'LensCenter',
  89889. 'Scale',
  89890. 'ScaleIn',
  89891. 'HmdWarpParam'
  89892. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  89893. _this._isRightEye = isRightEye;
  89894. _this._distortionFactors = vrMetrics.distortionK;
  89895. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  89896. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  89897. _this.adaptScaleToCurrentViewport = true;
  89898. _this.onSizeChangedObservable.add(function () {
  89899. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  89900. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  89901. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  89902. });
  89903. _this.onApplyObservable.add(function (effect) {
  89904. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  89905. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  89906. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  89907. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  89908. });
  89909. return _this;
  89910. }
  89911. return VRDistortionCorrectionPostProcess;
  89912. }(BABYLON.PostProcess));
  89913. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  89914. })(BABYLON || (BABYLON = {}));
  89915. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  89916. var BABYLON;
  89917. (function (BABYLON) {
  89918. /**
  89919. * Postprocess used to generate anaglyphic rendering
  89920. */
  89921. var AnaglyphPostProcess = /** @class */ (function (_super) {
  89922. __extends(AnaglyphPostProcess, _super);
  89923. /**
  89924. * Creates a new AnaglyphPostProcess
  89925. * @param name defines postprocess name
  89926. * @param options defines creation options or target ratio scale
  89927. * @param rigCameras defines cameras using this postprocess
  89928. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  89929. * @param engine defines hosting engine
  89930. * @param reusable defines if the postprocess will be reused multiple times per frame
  89931. */
  89932. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  89933. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  89934. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89935. _this.onApplyObservable.add(function (effect) {
  89936. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  89937. });
  89938. return _this;
  89939. }
  89940. return AnaglyphPostProcess;
  89941. }(BABYLON.PostProcess));
  89942. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  89943. })(BABYLON || (BABYLON = {}));
  89944. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  89945. var BABYLON;
  89946. (function (BABYLON) {
  89947. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  89948. __extends(StereoscopicInterlacePostProcess, _super);
  89949. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  89950. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  89951. _this._passedProcess = rigCameras[0]._rigPostProcess;
  89952. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89953. _this.onSizeChangedObservable.add(function () {
  89954. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  89955. });
  89956. _this.onApplyObservable.add(function (effect) {
  89957. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  89958. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  89959. });
  89960. return _this;
  89961. }
  89962. return StereoscopicInterlacePostProcess;
  89963. }(BABYLON.PostProcess));
  89964. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  89965. })(BABYLON || (BABYLON = {}));
  89966. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  89967. var BABYLON;
  89968. (function (BABYLON) {
  89969. /**
  89970. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  89971. * Screen rotation is taken into account.
  89972. */
  89973. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  89974. function FreeCameraDeviceOrientationInput() {
  89975. var _this = this;
  89976. this._screenOrientationAngle = 0;
  89977. this._screenQuaternion = new BABYLON.Quaternion();
  89978. this._alpha = 0;
  89979. this._beta = 0;
  89980. this._gamma = 0;
  89981. this._orientationChanged = function () {
  89982. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  89983. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  89984. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  89985. };
  89986. this._deviceOrientation = function (evt) {
  89987. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  89988. _this._beta = evt.beta !== null ? evt.beta : 0;
  89989. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  89990. };
  89991. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  89992. this._orientationChanged();
  89993. }
  89994. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  89995. get: function () {
  89996. return this._camera;
  89997. },
  89998. set: function (camera) {
  89999. this._camera = camera;
  90000. if (this._camera != null && !this._camera.rotationQuaternion) {
  90001. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90002. }
  90003. },
  90004. enumerable: true,
  90005. configurable: true
  90006. });
  90007. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90008. window.addEventListener("orientationchange", this._orientationChanged);
  90009. window.addEventListener("deviceorientation", this._deviceOrientation);
  90010. //In certain cases, the attach control is called AFTER orientation was changed,
  90011. //So this is needed.
  90012. this._orientationChanged();
  90013. };
  90014. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90015. window.removeEventListener("orientationchange", this._orientationChanged);
  90016. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90017. };
  90018. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90019. //if no device orientation provided, don't update the rotation.
  90020. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90021. if (!this._alpha)
  90022. return;
  90023. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90024. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90025. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90026. //Mirror on XY Plane
  90027. this._camera.rotationQuaternion.z *= -1;
  90028. this._camera.rotationQuaternion.w *= -1;
  90029. };
  90030. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90031. return "FreeCameraDeviceOrientationInput";
  90032. };
  90033. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90034. return "deviceOrientation";
  90035. };
  90036. return FreeCameraDeviceOrientationInput;
  90037. }());
  90038. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90039. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90040. })(BABYLON || (BABYLON = {}));
  90041. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90042. var BABYLON;
  90043. (function (BABYLON) {
  90044. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90045. function ArcRotateCameraVRDeviceOrientationInput() {
  90046. this.alphaCorrection = 1;
  90047. this.betaCorrection = 1;
  90048. this.gammaCorrection = 1;
  90049. this._alpha = 0;
  90050. this._gamma = 0;
  90051. this._dirty = false;
  90052. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90053. }
  90054. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90055. this.camera.attachControl(element, noPreventDefault);
  90056. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90057. };
  90058. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90059. if (evt.alpha !== null) {
  90060. this._alpha = +evt.alpha | 0;
  90061. }
  90062. if (evt.gamma !== null) {
  90063. this._gamma = +evt.gamma | 0;
  90064. }
  90065. this._dirty = true;
  90066. };
  90067. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90068. if (this._dirty) {
  90069. this._dirty = false;
  90070. if (this._gamma < 0) {
  90071. this._gamma = 180 + this._gamma;
  90072. }
  90073. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90074. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90075. }
  90076. };
  90077. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90078. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90079. };
  90080. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90081. return "ArcRotateCameraVRDeviceOrientationInput";
  90082. };
  90083. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90084. return "VRDeviceOrientation";
  90085. };
  90086. return ArcRotateCameraVRDeviceOrientationInput;
  90087. }());
  90088. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90089. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90090. })(BABYLON || (BABYLON = {}));
  90091. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90092. var BABYLON;
  90093. (function (BABYLON) {
  90094. var VRCameraMetrics = /** @class */ (function () {
  90095. function VRCameraMetrics() {
  90096. this.compensateDistortion = true;
  90097. }
  90098. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90099. get: function () {
  90100. return this.hResolution / (2 * this.vResolution);
  90101. },
  90102. enumerable: true,
  90103. configurable: true
  90104. });
  90105. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90106. get: function () {
  90107. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90108. },
  90109. enumerable: true,
  90110. configurable: true
  90111. });
  90112. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90113. get: function () {
  90114. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90115. var h = (4 * meters) / this.hScreenSize;
  90116. return BABYLON.Matrix.Translation(h, 0, 0);
  90117. },
  90118. enumerable: true,
  90119. configurable: true
  90120. });
  90121. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90122. get: function () {
  90123. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90124. var h = (4 * meters) / this.hScreenSize;
  90125. return BABYLON.Matrix.Translation(-h, 0, 0);
  90126. },
  90127. enumerable: true,
  90128. configurable: true
  90129. });
  90130. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90131. get: function () {
  90132. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90133. },
  90134. enumerable: true,
  90135. configurable: true
  90136. });
  90137. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90138. get: function () {
  90139. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90140. },
  90141. enumerable: true,
  90142. configurable: true
  90143. });
  90144. VRCameraMetrics.GetDefault = function () {
  90145. var result = new VRCameraMetrics();
  90146. result.hResolution = 1280;
  90147. result.vResolution = 800;
  90148. result.hScreenSize = 0.149759993;
  90149. result.vScreenSize = 0.0935999975;
  90150. result.vScreenCenter = 0.0467999987;
  90151. result.eyeToScreenDistance = 0.0410000011;
  90152. result.lensSeparationDistance = 0.0635000020;
  90153. result.interpupillaryDistance = 0.0640000030;
  90154. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90155. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90156. result.postProcessScaleFactor = 1.714605507808412;
  90157. result.lensCenterOffset = 0.151976421;
  90158. return result;
  90159. };
  90160. return VRCameraMetrics;
  90161. }());
  90162. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90163. })(BABYLON || (BABYLON = {}));
  90164. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90165. var BABYLON;
  90166. (function (BABYLON) {
  90167. /**
  90168. * This represents a WebVR camera.
  90169. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90170. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90171. */
  90172. var WebVRFreeCamera = /** @class */ (function (_super) {
  90173. __extends(WebVRFreeCamera, _super);
  90174. /**
  90175. * Instantiates a WebVRFreeCamera.
  90176. * @param name The name of the WebVRFreeCamera
  90177. * @param position The starting anchor position for the camera
  90178. * @param scene The scene the camera belongs to
  90179. * @param webVROptions a set of customizable options for the webVRCamera
  90180. */
  90181. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90182. if (webVROptions === void 0) { webVROptions = {}; }
  90183. var _this = _super.call(this, name, position, scene) || this;
  90184. _this.webVROptions = webVROptions;
  90185. /**
  90186. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90187. */
  90188. _this._vrDevice = null;
  90189. /**
  90190. * The rawPose of the vrDevice.
  90191. */
  90192. _this.rawPose = null;
  90193. _this._specsVersion = "1.1";
  90194. _this._attached = false;
  90195. _this._descendants = [];
  90196. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90197. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90198. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90199. _this._standingMatrix = null;
  90200. /**
  90201. * Represents device position in babylon space.
  90202. */
  90203. _this.devicePosition = BABYLON.Vector3.Zero();
  90204. /**
  90205. * Represents device rotation in babylon space.
  90206. */
  90207. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90208. /**
  90209. * The scale of the device to be used when translating from device space to babylon space.
  90210. */
  90211. _this.deviceScaleFactor = 1;
  90212. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90213. _this._worldToDevice = BABYLON.Matrix.Identity();
  90214. /**
  90215. * References to the webVR controllers for the vrDevice.
  90216. */
  90217. _this.controllers = [];
  90218. /**
  90219. * Emits an event when a controller is attached.
  90220. */
  90221. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90222. /**
  90223. * Emits an event when a controller's mesh has been loaded;
  90224. */
  90225. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90226. /**
  90227. * If the rig cameras be used as parent instead of this camera.
  90228. */
  90229. _this.rigParenting = true;
  90230. _this._defaultHeight = undefined;
  90231. _this._workingVector = BABYLON.Vector3.Zero();
  90232. _this._oneVector = BABYLON.Vector3.One();
  90233. _this._workingMatrix = BABYLON.Matrix.Identity();
  90234. _this._cache.position = BABYLON.Vector3.Zero();
  90235. if (webVROptions.defaultHeight) {
  90236. _this._defaultHeight = webVROptions.defaultHeight;
  90237. _this.position.y = _this._defaultHeight;
  90238. }
  90239. _this.minZ = 0.1;
  90240. //legacy support - the compensation boolean was removed.
  90241. if (arguments.length === 5) {
  90242. _this.webVROptions = arguments[4];
  90243. }
  90244. // default webVR options
  90245. if (_this.webVROptions.trackPosition == undefined) {
  90246. _this.webVROptions.trackPosition = true;
  90247. }
  90248. if (_this.webVROptions.controllerMeshes == undefined) {
  90249. _this.webVROptions.controllerMeshes = true;
  90250. }
  90251. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90252. _this.webVROptions.defaultLightingOnControllers = true;
  90253. }
  90254. _this.rotationQuaternion = new BABYLON.Quaternion();
  90255. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90256. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90257. }
  90258. //enable VR
  90259. var engine = _this.getEngine();
  90260. _this._onVREnabled = function (success) { if (success) {
  90261. _this.initControllers();
  90262. } };
  90263. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90264. engine.initWebVR().add(function (event) {
  90265. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90266. return;
  90267. }
  90268. _this._vrDevice = event.vrDisplay;
  90269. //reset the rig parameters.
  90270. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90271. if (_this._attached) {
  90272. _this.getEngine().enableVR();
  90273. }
  90274. });
  90275. if (typeof (VRFrameData) !== "undefined")
  90276. _this._frameData = new VRFrameData();
  90277. /**
  90278. * The idea behind the following lines:
  90279. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90280. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90281. * the second will not show it correctly.
  90282. *
  90283. * To solve this - each object that has the camera as parent will be added to a protected array.
  90284. * When the rig camera renders, it will take this array and set all of those to be its children.
  90285. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90286. * Amazing!
  90287. */
  90288. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90289. if (camera.parent === _this && _this.rigParenting) {
  90290. _this._descendants = _this.getDescendants(true, function (n) {
  90291. // don't take the cameras or the controllers!
  90292. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90293. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90294. return !isController && !isRigCamera;
  90295. });
  90296. _this._descendants.forEach(function (node) {
  90297. node.parent = camera;
  90298. });
  90299. }
  90300. });
  90301. scene.onAfterCameraRenderObservable.add(function (camera) {
  90302. if (camera.parent === _this && _this.rigParenting) {
  90303. _this._descendants.forEach(function (node) {
  90304. node.parent = _this;
  90305. });
  90306. }
  90307. });
  90308. return _this;
  90309. }
  90310. /**
  90311. * Gets the device distance from the ground in meters.
  90312. * @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.
  90313. */
  90314. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90315. if (this._standingMatrix) {
  90316. // Add standing matrix offset to get real offset from ground in room
  90317. this._standingMatrix.getTranslationToRef(this._workingVector);
  90318. return this._deviceRoomPosition.y + this._workingVector.y;
  90319. }
  90320. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90321. return this._defaultHeight || 0;
  90322. };
  90323. /**
  90324. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90325. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90326. */
  90327. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90328. var _this = this;
  90329. if (callback === void 0) { callback = function (bool) { }; }
  90330. // Use standing matrix if available
  90331. this.getEngine().initWebVRAsync().then(function (result) {
  90332. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90333. callback(false);
  90334. }
  90335. else {
  90336. _this._standingMatrix = new BABYLON.Matrix();
  90337. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90338. if (!_this.getScene().useRightHandedSystem) {
  90339. [2, 6, 8, 9, 14].forEach(function (num) {
  90340. if (_this._standingMatrix) {
  90341. _this._standingMatrix.m[num] *= -1;
  90342. }
  90343. });
  90344. }
  90345. callback(true);
  90346. }
  90347. });
  90348. };
  90349. /**
  90350. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90351. * @returns A promise with a boolean set to if the standing matrix is supported.
  90352. */
  90353. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90354. var _this = this;
  90355. return new Promise(function (res, rej) {
  90356. _this.useStandingMatrix(function (supported) {
  90357. res(supported);
  90358. });
  90359. });
  90360. };
  90361. /**
  90362. * Disposes the camera
  90363. */
  90364. WebVRFreeCamera.prototype.dispose = function () {
  90365. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90366. _super.prototype.dispose.call(this);
  90367. };
  90368. /**
  90369. * Gets a vrController by name.
  90370. * @param name The name of the controller to retreive
  90371. * @returns the controller matching the name specified or null if not found
  90372. */
  90373. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90374. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90375. var gp = _a[_i];
  90376. if (gp.hand === name) {
  90377. return gp;
  90378. }
  90379. }
  90380. return null;
  90381. };
  90382. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90383. /**
  90384. * The controller corrisponding to the users left hand.
  90385. */
  90386. get: function () {
  90387. if (!this._leftController) {
  90388. this._leftController = this.getControllerByName("left");
  90389. }
  90390. return this._leftController;
  90391. },
  90392. enumerable: true,
  90393. configurable: true
  90394. });
  90395. ;
  90396. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  90397. /**
  90398. * The controller corrisponding to the users right hand.
  90399. */
  90400. get: function () {
  90401. if (!this._rightController) {
  90402. this._rightController = this.getControllerByName("right");
  90403. }
  90404. return this._rightController;
  90405. },
  90406. enumerable: true,
  90407. configurable: true
  90408. });
  90409. ;
  90410. /**
  90411. * Casts a ray forward from the vrCamera's gaze.
  90412. * @param length Length of the ray (default: 100)
  90413. * @returns the ray corrisponding to the gaze
  90414. */
  90415. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  90416. if (length === void 0) { length = 100; }
  90417. if (this.leftCamera) {
  90418. // Use left eye to avoid computation to compute center on every call
  90419. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  90420. }
  90421. else {
  90422. return _super.prototype.getForwardRay.call(this, length);
  90423. }
  90424. };
  90425. /**
  90426. * Updates the camera based on device's frame data
  90427. */
  90428. WebVRFreeCamera.prototype._checkInputs = function () {
  90429. if (this._vrDevice && this._vrDevice.isPresenting) {
  90430. this._vrDevice.getFrameData(this._frameData);
  90431. this.updateFromDevice(this._frameData.pose);
  90432. }
  90433. _super.prototype._checkInputs.call(this);
  90434. };
  90435. /**
  90436. * Updates the poseControlled values based on the input device pose.
  90437. * @param poseData Pose coming from the device
  90438. */
  90439. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  90440. if (poseData && poseData.orientation) {
  90441. this.rawPose = poseData;
  90442. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  90443. if (this.getScene().useRightHandedSystem) {
  90444. this._deviceRoomRotationQuaternion.z *= -1;
  90445. this._deviceRoomRotationQuaternion.w *= -1;
  90446. }
  90447. if (this.webVROptions.trackPosition && this.rawPose.position) {
  90448. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  90449. if (this.getScene().useRightHandedSystem) {
  90450. this._deviceRoomPosition.z *= -1;
  90451. }
  90452. }
  90453. }
  90454. };
  90455. /**
  90456. * WebVR's attach control will start broadcasting frames to the device.
  90457. * Note that in certain browsers (chrome for example) this function must be called
  90458. * within a user-interaction callback. Example:
  90459. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  90460. *
  90461. * @param element html element to attach the vrDevice to
  90462. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  90463. */
  90464. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  90465. _super.prototype.attachControl.call(this, element, noPreventDefault);
  90466. this._attached = true;
  90467. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  90468. if (this._vrDevice) {
  90469. this.getEngine().enableVR();
  90470. }
  90471. };
  90472. /**
  90473. * Detaches the camera from the html element and disables VR
  90474. *
  90475. * @param element html element to detach from
  90476. */
  90477. WebVRFreeCamera.prototype.detachControl = function (element) {
  90478. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  90479. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  90480. _super.prototype.detachControl.call(this, element);
  90481. this._attached = false;
  90482. this.getEngine().disableVR();
  90483. };
  90484. /**
  90485. * @returns the name of this class
  90486. */
  90487. WebVRFreeCamera.prototype.getClassName = function () {
  90488. return "WebVRFreeCamera";
  90489. };
  90490. /**
  90491. * Calls resetPose on the vrDisplay
  90492. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  90493. */
  90494. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  90495. //uses the vrDisplay's "resetPose()".
  90496. //pitch and roll won't be affected.
  90497. this._vrDevice.resetPose();
  90498. };
  90499. /**
  90500. * Updates the rig cameras (left and right eye)
  90501. */
  90502. WebVRFreeCamera.prototype._updateRigCameras = function () {
  90503. var camLeft = this._rigCameras[0];
  90504. var camRight = this._rigCameras[1];
  90505. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90506. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  90507. camLeft.position.copyFrom(this._deviceRoomPosition);
  90508. camRight.position.copyFrom(this._deviceRoomPosition);
  90509. };
  90510. /**
  90511. * Updates the cached values of the camera
  90512. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  90513. */
  90514. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  90515. var _this = this;
  90516. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  90517. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  90518. if (!this.updateCacheCalled) {
  90519. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  90520. this.updateCacheCalled = true;
  90521. this.update();
  90522. }
  90523. // Set working vector to the device position in room space rotated by the new rotation
  90524. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  90525. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  90526. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  90527. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  90528. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  90529. // Add translation from anchor position
  90530. this._deviceToWorld.getTranslationToRef(this._workingVector);
  90531. this._workingVector.addInPlace(this.position);
  90532. this._workingVector.subtractInPlace(this._cache.position);
  90533. this._deviceToWorld.setTranslation(this._workingVector);
  90534. // Set an inverted matrix to be used when updating the camera
  90535. this._deviceToWorld.invertToRef(this._worldToDevice);
  90536. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  90537. this.controllers.forEach(function (controller) {
  90538. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  90539. controller.update();
  90540. });
  90541. }
  90542. if (!ignoreParentClass) {
  90543. _super.prototype._updateCache.call(this);
  90544. }
  90545. this.updateCacheCalled = false;
  90546. };
  90547. /**
  90548. * Updates the current device position and rotation in the babylon world
  90549. */
  90550. WebVRFreeCamera.prototype.update = function () {
  90551. // Get current device position in babylon world
  90552. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  90553. // Get current device rotation in babylon world
  90554. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  90555. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  90556. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  90557. _super.prototype.update.call(this);
  90558. };
  90559. /**
  90560. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  90561. * @returns an identity matrix
  90562. */
  90563. WebVRFreeCamera.prototype._getViewMatrix = function () {
  90564. return BABYLON.Matrix.Identity();
  90565. };
  90566. /**
  90567. * This function is called by the two RIG cameras.
  90568. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  90569. */
  90570. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  90571. var _this = this;
  90572. // Update the parent camera prior to using a child camera to avoid desynchronization
  90573. var parentCamera = this._cameraRigParams["parentCamera"];
  90574. parentCamera._updateCache();
  90575. //WebVR 1.1
  90576. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  90577. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  90578. if (!this.getScene().useRightHandedSystem) {
  90579. [2, 6, 8, 9, 14].forEach(function (num) {
  90580. _this._webvrViewMatrix.m[num] *= -1;
  90581. });
  90582. }
  90583. // update the camera rotation matrix
  90584. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  90585. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  90586. // Computing target and final matrix
  90587. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  90588. // should the view matrix be updated with scale and position offset?
  90589. if (parentCamera.deviceScaleFactor !== 1) {
  90590. this._webvrViewMatrix.invert();
  90591. // scale the position, if set
  90592. if (parentCamera.deviceScaleFactor) {
  90593. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  90594. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  90595. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  90596. }
  90597. this._webvrViewMatrix.invert();
  90598. }
  90599. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  90600. // Compute global position
  90601. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  90602. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  90603. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  90604. this._workingMatrix.getTranslationToRef(this._globalPosition);
  90605. this._markSyncedWithParent();
  90606. return this._webvrViewMatrix;
  90607. };
  90608. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  90609. var _this = this;
  90610. var parentCamera = this.parent;
  90611. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  90612. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  90613. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  90614. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  90615. //babylon compatible matrix
  90616. if (!this.getScene().useRightHandedSystem) {
  90617. [8, 9, 10, 11].forEach(function (num) {
  90618. _this._projectionMatrix.m[num] *= -1;
  90619. });
  90620. }
  90621. return this._projectionMatrix;
  90622. };
  90623. /**
  90624. * Initializes the controllers and their meshes
  90625. */
  90626. WebVRFreeCamera.prototype.initControllers = function () {
  90627. var _this = this;
  90628. this.controllers = [];
  90629. var manager = this.getScene().gamepadManager;
  90630. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  90631. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90632. var webVrController = gamepad;
  90633. if (webVrController.defaultModel) {
  90634. webVrController.defaultModel.setEnabled(false);
  90635. }
  90636. if (webVrController.hand === "right") {
  90637. _this._rightController = null;
  90638. }
  90639. if (webVrController.hand === "left") {
  90640. _this._leftController = null;
  90641. }
  90642. var controllerIndex = _this.controllers.indexOf(webVrController);
  90643. if (controllerIndex !== -1) {
  90644. _this.controllers.splice(controllerIndex, 1);
  90645. }
  90646. }
  90647. });
  90648. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  90649. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  90650. var webVrController_1 = gamepad;
  90651. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  90652. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  90653. if (_this.webVROptions.controllerMeshes) {
  90654. if (webVrController_1.defaultModel) {
  90655. webVrController_1.defaultModel.setEnabled(true);
  90656. }
  90657. else {
  90658. // Load the meshes
  90659. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  90660. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  90661. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  90662. if (_this.webVROptions.defaultLightingOnControllers) {
  90663. if (!_this._lightOnControllers) {
  90664. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  90665. }
  90666. var activateLightOnSubMeshes_1 = function (mesh, light) {
  90667. var children = mesh.getChildren();
  90668. if (children.length !== 0) {
  90669. children.forEach(function (mesh) {
  90670. light.includedOnlyMeshes.push(mesh);
  90671. activateLightOnSubMeshes_1(mesh, light);
  90672. });
  90673. }
  90674. };
  90675. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  90676. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  90677. }
  90678. });
  90679. }
  90680. }
  90681. webVrController_1.attachToPoseControlledCamera(_this);
  90682. // since this is async - sanity check. Is the controller already stored?
  90683. if (_this.controllers.indexOf(webVrController_1) === -1) {
  90684. //add to the controllers array
  90685. _this.controllers.push(webVrController_1);
  90686. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  90687. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  90688. // So we're overriding setting left & right manually to be sure
  90689. var firstViveWandDetected = false;
  90690. for (var i = 0; i < _this.controllers.length; i++) {
  90691. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  90692. if (!firstViveWandDetected) {
  90693. firstViveWandDetected = true;
  90694. _this.controllers[i].hand = "left";
  90695. }
  90696. else {
  90697. _this.controllers[i].hand = "right";
  90698. }
  90699. }
  90700. }
  90701. //did we find enough controllers? Great! let the developer know.
  90702. if (_this.controllers.length >= 2) {
  90703. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  90704. }
  90705. }
  90706. }
  90707. });
  90708. };
  90709. return WebVRFreeCamera;
  90710. }(BABYLON.FreeCamera));
  90711. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  90712. })(BABYLON || (BABYLON = {}));
  90713. //# sourceMappingURL=babylon.webVRCamera.js.map
  90714. var BABYLON;
  90715. (function (BABYLON) {
  90716. // We're mainly based on the logic defined into the FreeCamera code
  90717. /**
  90718. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  90719. * being tilted forward or back and left or right.
  90720. */
  90721. var DeviceOrientationCamera = /** @class */ (function (_super) {
  90722. __extends(DeviceOrientationCamera, _super);
  90723. /**
  90724. * Creates a new device orientation camera
  90725. * @param name The name of the camera
  90726. * @param position The start position camera
  90727. * @param scene The scene the camera belongs to
  90728. */
  90729. function DeviceOrientationCamera(name, position, scene) {
  90730. var _this = _super.call(this, name, position, scene) || this;
  90731. _this._quaternionCache = new BABYLON.Quaternion();
  90732. _this.inputs.addDeviceOrientation();
  90733. return _this;
  90734. }
  90735. /**
  90736. * Gets the current instance class name ("DeviceOrientationCamera").
  90737. * This helps avoiding instanceof at run time.
  90738. * @returns the class name
  90739. */
  90740. DeviceOrientationCamera.prototype.getClassName = function () {
  90741. return "DeviceOrientationCamera";
  90742. };
  90743. /**
  90744. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  90745. */
  90746. DeviceOrientationCamera.prototype._checkInputs = function () {
  90747. _super.prototype._checkInputs.call(this);
  90748. this._quaternionCache.copyFrom(this.rotationQuaternion);
  90749. if (this._initialQuaternion) {
  90750. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90751. }
  90752. };
  90753. /**
  90754. * Reset the camera to its default orientation on the specified axis only.
  90755. * @param axis The axis to reset
  90756. */
  90757. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  90758. var _this = this;
  90759. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  90760. //can only work if this camera has a rotation quaternion already.
  90761. if (!this.rotationQuaternion)
  90762. return;
  90763. if (!this._initialQuaternion) {
  90764. this._initialQuaternion = new BABYLON.Quaternion();
  90765. }
  90766. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  90767. ['x', 'y', 'z'].forEach(function (axisName) {
  90768. if (!axis[axisName]) {
  90769. _this._initialQuaternion[axisName] = 0;
  90770. }
  90771. else {
  90772. _this._initialQuaternion[axisName] *= -1;
  90773. }
  90774. });
  90775. this._initialQuaternion.normalize();
  90776. //force rotation update
  90777. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  90778. };
  90779. return DeviceOrientationCamera;
  90780. }(BABYLON.FreeCamera));
  90781. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  90782. })(BABYLON || (BABYLON = {}));
  90783. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  90784. var BABYLON;
  90785. (function (BABYLON) {
  90786. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  90787. __extends(VRDeviceOrientationFreeCamera, _super);
  90788. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90789. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90790. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90791. var _this = _super.call(this, name, position, scene) || this;
  90792. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90793. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90794. return _this;
  90795. }
  90796. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  90797. return "VRDeviceOrientationFreeCamera";
  90798. };
  90799. return VRDeviceOrientationFreeCamera;
  90800. }(BABYLON.DeviceOrientationCamera));
  90801. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  90802. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  90803. __extends(VRDeviceOrientationGamepadCamera, _super);
  90804. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  90805. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90806. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90807. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  90808. _this.inputs.addGamepad();
  90809. return _this;
  90810. }
  90811. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  90812. return "VRDeviceOrientationGamepadCamera";
  90813. };
  90814. return VRDeviceOrientationGamepadCamera;
  90815. }(VRDeviceOrientationFreeCamera));
  90816. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  90817. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  90818. __extends(VRDeviceOrientationArcRotateCamera, _super);
  90819. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  90820. if (compensateDistortion === void 0) { compensateDistortion = true; }
  90821. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  90822. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90823. vrCameraMetrics.compensateDistortion = compensateDistortion;
  90824. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  90825. _this.inputs.addVRDeviceOrientation();
  90826. return _this;
  90827. }
  90828. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  90829. return "VRDeviceOrientationArcRotateCamera";
  90830. };
  90831. return VRDeviceOrientationArcRotateCamera;
  90832. }(BABYLON.ArcRotateCamera));
  90833. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  90834. })(BABYLON || (BABYLON = {}));
  90835. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  90836. var BABYLON;
  90837. (function (BABYLON) {
  90838. /**
  90839. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  90840. */
  90841. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  90842. __extends(AnaglyphFreeCamera, _super);
  90843. /**
  90844. * Creates a new AnaglyphFreeCamera
  90845. * @param name defines camera name
  90846. * @param position defines initial position
  90847. * @param interaxialDistance defines distance between each color axis
  90848. * @param scene defines the hosting scene
  90849. */
  90850. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  90851. var _this = _super.call(this, name, position, scene) || this;
  90852. _this.interaxialDistance = interaxialDistance;
  90853. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90854. return _this;
  90855. }
  90856. /**
  90857. * Gets camera class name
  90858. * @returns AnaglyphFreeCamera
  90859. */
  90860. AnaglyphFreeCamera.prototype.getClassName = function () {
  90861. return "AnaglyphFreeCamera";
  90862. };
  90863. return AnaglyphFreeCamera;
  90864. }(BABYLON.FreeCamera));
  90865. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  90866. /**
  90867. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  90868. */
  90869. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  90870. __extends(AnaglyphArcRotateCamera, _super);
  90871. /**
  90872. * Creates a new AnaglyphArcRotateCamera
  90873. * @param name defines camera name
  90874. * @param alpha defines alpha angle (in radians)
  90875. * @param beta defines beta angle (in radians)
  90876. * @param radius defines radius
  90877. * @param target defines camera target
  90878. * @param interaxialDistance defines distance between each color axis
  90879. * @param scene defines the hosting scene
  90880. */
  90881. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  90882. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  90883. _this.interaxialDistance = interaxialDistance;
  90884. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90885. return _this;
  90886. }
  90887. /**
  90888. * Gets camera class name
  90889. * @returns AnaglyphArcRotateCamera
  90890. */
  90891. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  90892. return "AnaglyphArcRotateCamera";
  90893. };
  90894. return AnaglyphArcRotateCamera;
  90895. }(BABYLON.ArcRotateCamera));
  90896. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  90897. /**
  90898. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  90899. */
  90900. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  90901. __extends(AnaglyphGamepadCamera, _super);
  90902. /**
  90903. * Creates a new AnaglyphGamepadCamera
  90904. * @param name defines camera name
  90905. * @param position defines initial position
  90906. * @param interaxialDistance defines distance between each color axis
  90907. * @param scene defines the hosting scene
  90908. */
  90909. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  90910. var _this = _super.call(this, name, position, scene) || this;
  90911. _this.interaxialDistance = interaxialDistance;
  90912. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90913. return _this;
  90914. }
  90915. /**
  90916. * Gets camera class name
  90917. * @returns AnaglyphGamepadCamera
  90918. */
  90919. AnaglyphGamepadCamera.prototype.getClassName = function () {
  90920. return "AnaglyphGamepadCamera";
  90921. };
  90922. return AnaglyphGamepadCamera;
  90923. }(BABYLON.GamepadCamera));
  90924. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  90925. /**
  90926. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  90927. */
  90928. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  90929. __extends(AnaglyphUniversalCamera, _super);
  90930. /**
  90931. * Creates a new AnaglyphUniversalCamera
  90932. * @param name defines camera name
  90933. * @param position defines initial position
  90934. * @param interaxialDistance defines distance between each color axis
  90935. * @param scene defines the hosting scene
  90936. */
  90937. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  90938. var _this = _super.call(this, name, position, scene) || this;
  90939. _this.interaxialDistance = interaxialDistance;
  90940. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  90941. return _this;
  90942. }
  90943. /**
  90944. * Gets camera class name
  90945. * @returns AnaglyphUniversalCamera
  90946. */
  90947. AnaglyphUniversalCamera.prototype.getClassName = function () {
  90948. return "AnaglyphUniversalCamera";
  90949. };
  90950. return AnaglyphUniversalCamera;
  90951. }(BABYLON.UniversalCamera));
  90952. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  90953. /**
  90954. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  90955. */
  90956. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  90957. __extends(StereoscopicFreeCamera, _super);
  90958. /**
  90959. * Creates a new StereoscopicFreeCamera
  90960. * @param name defines camera name
  90961. * @param position defines initial position
  90962. * @param interaxialDistance defines distance between each color axis
  90963. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90964. * @param scene defines the hosting scene
  90965. */
  90966. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  90967. var _this = _super.call(this, name, position, scene) || this;
  90968. _this.interaxialDistance = interaxialDistance;
  90969. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  90970. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  90971. return _this;
  90972. }
  90973. /**
  90974. * Gets camera class name
  90975. * @returns StereoscopicFreeCamera
  90976. */
  90977. StereoscopicFreeCamera.prototype.getClassName = function () {
  90978. return "StereoscopicFreeCamera";
  90979. };
  90980. return StereoscopicFreeCamera;
  90981. }(BABYLON.FreeCamera));
  90982. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  90983. /**
  90984. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  90985. */
  90986. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  90987. __extends(StereoscopicArcRotateCamera, _super);
  90988. /**
  90989. * Creates a new StereoscopicArcRotateCamera
  90990. * @param name defines camera name
  90991. * @param alpha defines alpha angle (in radians)
  90992. * @param beta defines beta angle (in radians)
  90993. * @param radius defines radius
  90994. * @param target defines camera target
  90995. * @param interaxialDistance defines distance between each color axis
  90996. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  90997. * @param scene defines the hosting scene
  90998. */
  90999. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91000. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91001. _this.interaxialDistance = interaxialDistance;
  91002. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91003. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91004. return _this;
  91005. }
  91006. /**
  91007. * Gets camera class name
  91008. * @returns StereoscopicArcRotateCamera
  91009. */
  91010. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91011. return "StereoscopicArcRotateCamera";
  91012. };
  91013. return StereoscopicArcRotateCamera;
  91014. }(BABYLON.ArcRotateCamera));
  91015. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91016. /**
  91017. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91018. */
  91019. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91020. __extends(StereoscopicGamepadCamera, _super);
  91021. /**
  91022. * Creates a new StereoscopicGamepadCamera
  91023. * @param name defines camera name
  91024. * @param position defines initial position
  91025. * @param interaxialDistance defines distance between each color axis
  91026. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91027. * @param scene defines the hosting scene
  91028. */
  91029. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91030. var _this = _super.call(this, name, position, scene) || this;
  91031. _this.interaxialDistance = interaxialDistance;
  91032. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91033. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91034. return _this;
  91035. }
  91036. /**
  91037. * Gets camera class name
  91038. * @returns StereoscopicGamepadCamera
  91039. */
  91040. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91041. return "StereoscopicGamepadCamera";
  91042. };
  91043. return StereoscopicGamepadCamera;
  91044. }(BABYLON.GamepadCamera));
  91045. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91046. /**
  91047. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91048. */
  91049. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91050. __extends(StereoscopicUniversalCamera, _super);
  91051. /**
  91052. * Creates a new StereoscopicUniversalCamera
  91053. * @param name defines camera name
  91054. * @param position defines initial position
  91055. * @param interaxialDistance defines distance between each color axis
  91056. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91057. * @param scene defines the hosting scene
  91058. */
  91059. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91060. var _this = _super.call(this, name, position, scene) || this;
  91061. _this.interaxialDistance = interaxialDistance;
  91062. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91063. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91064. return _this;
  91065. }
  91066. /**
  91067. * Gets camera class name
  91068. * @returns StereoscopicUniversalCamera
  91069. */
  91070. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91071. return "StereoscopicUniversalCamera";
  91072. };
  91073. return StereoscopicUniversalCamera;
  91074. }(BABYLON.UniversalCamera));
  91075. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91076. })(BABYLON || (BABYLON = {}));
  91077. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91078. var BABYLON;
  91079. (function (BABYLON) {
  91080. var VRExperienceHelperGazer = /** @class */ (function () {
  91081. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91082. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91083. this.scene = scene;
  91084. this._pointerDownOnMeshAsked = false;
  91085. this._isActionableMesh = false;
  91086. this._teleportationRequestInitiated = false;
  91087. this._teleportationBackRequestInitiated = false;
  91088. this._rotationRightAsked = false;
  91089. this._rotationLeftAsked = false;
  91090. this._dpadPressed = true;
  91091. this._activePointer = false;
  91092. this._id = VRExperienceHelperGazer._idCounter++;
  91093. // Gaze tracker
  91094. if (!gazeTrackerToClone) {
  91095. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91096. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91097. this._gazeTracker.isPickable = false;
  91098. this._gazeTracker.isVisible = false;
  91099. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91100. targetMat.specularColor = BABYLON.Color3.Black();
  91101. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91102. targetMat.backFaceCulling = false;
  91103. this._gazeTracker.material = targetMat;
  91104. }
  91105. else {
  91106. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91107. }
  91108. }
  91109. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91110. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91111. };
  91112. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91113. this._pointerDownOnMeshAsked = true;
  91114. if (this._currentHit) {
  91115. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91116. }
  91117. };
  91118. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91119. if (this._currentHit) {
  91120. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91121. }
  91122. this._pointerDownOnMeshAsked = false;
  91123. };
  91124. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91125. this._activePointer = true;
  91126. };
  91127. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91128. this._activePointer = false;
  91129. };
  91130. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91131. if (distance === void 0) { distance = 100; }
  91132. };
  91133. VRExperienceHelperGazer.prototype.dispose = function () {
  91134. this._interactionsEnabled = false;
  91135. this._teleportationEnabled = false;
  91136. if (this._gazeTracker) {
  91137. this._gazeTracker.dispose();
  91138. }
  91139. };
  91140. VRExperienceHelperGazer._idCounter = 0;
  91141. return VRExperienceHelperGazer;
  91142. }());
  91143. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91144. __extends(VRExperienceHelperControllerGazer, _super);
  91145. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91146. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91147. _this.webVRController = webVRController;
  91148. // Laser pointer
  91149. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91150. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91151. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91152. laserPointerMaterial.alpha = 0.6;
  91153. _this._laserPointer.material = laserPointerMaterial;
  91154. _this._laserPointer.rotation.x = Math.PI / 2;
  91155. _this._laserPointer.position.z = -0.5;
  91156. _this._laserPointer.isVisible = false;
  91157. _this._laserPointer.isPickable = false;
  91158. if (!webVRController.mesh) {
  91159. // Create an empty mesh that is used prior to loading the high quality model
  91160. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91161. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91162. preloadPointerPose.rotation.x = -0.7;
  91163. preloadMesh.addChild(preloadPointerPose);
  91164. webVRController.attachToMesh(preloadMesh);
  91165. }
  91166. _this._setLaserPointerParent(webVRController.mesh);
  91167. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91168. _this._setLaserPointerParent(mesh);
  91169. });
  91170. return _this;
  91171. }
  91172. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91173. return this.webVRController.getForwardRay(length);
  91174. };
  91175. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91176. _super.prototype._activatePointer.call(this);
  91177. this._laserPointer.isVisible = true;
  91178. };
  91179. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91180. _super.prototype._deactivatePointer.call(this);
  91181. this._laserPointer.isVisible = false;
  91182. };
  91183. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91184. this._laserPointer.material.emissiveColor = color;
  91185. };
  91186. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91187. var makeNotPick = function (root) {
  91188. root.name += " laserPointer";
  91189. root.isPickable = false;
  91190. root.getChildMeshes().forEach(function (c) {
  91191. makeNotPick(c);
  91192. });
  91193. };
  91194. makeNotPick(mesh);
  91195. var childMeshes = mesh.getChildMeshes();
  91196. this.webVRController._pointingPoseNode = null;
  91197. for (var i = 0; i < childMeshes.length; i++) {
  91198. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91199. mesh = childMeshes[i];
  91200. this.webVRController._pointingPoseNode = mesh;
  91201. break;
  91202. }
  91203. }
  91204. this._laserPointer.parent = mesh;
  91205. };
  91206. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91207. if (distance === void 0) { distance = 100; }
  91208. this._laserPointer.scaling.y = distance;
  91209. this._laserPointer.position.z = -distance / 2;
  91210. };
  91211. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91212. _super.prototype.dispose.call(this);
  91213. this._laserPointer.dispose();
  91214. if (this._meshAttachedObserver) {
  91215. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91216. }
  91217. };
  91218. return VRExperienceHelperControllerGazer;
  91219. }(VRExperienceHelperGazer));
  91220. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91221. __extends(VRExperienceHelperCameraGazer, _super);
  91222. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91223. var _this = _super.call(this, scene) || this;
  91224. _this.getCamera = getCamera;
  91225. return _this;
  91226. }
  91227. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91228. var camera = this.getCamera();
  91229. if (camera) {
  91230. return camera.getForwardRay(length);
  91231. }
  91232. else {
  91233. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91234. }
  91235. };
  91236. return VRExperienceHelperCameraGazer;
  91237. }(VRExperienceHelperGazer));
  91238. /**
  91239. * Helps to quickly add VR support to an existing scene.
  91240. * See http://doc.babylonjs.com/how_to/webvr_helper
  91241. */
  91242. var VRExperienceHelper = /** @class */ (function () {
  91243. /**
  91244. * Instantiates a VRExperienceHelper.
  91245. * Helps to quickly add VR support to an existing scene.
  91246. * @param scene The scene the VRExperienceHelper belongs to.
  91247. * @param webVROptions Options to modify the vr experience helper's behavior.
  91248. */
  91249. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91250. if (webVROptions === void 0) { webVROptions = {}; }
  91251. var _this = this;
  91252. this.webVROptions = webVROptions;
  91253. // Can the system support WebVR, even if a headset isn't plugged in?
  91254. this._webVRsupported = false;
  91255. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91256. this._webVRready = false;
  91257. // Are we waiting for the requestPresent callback to complete?
  91258. this._webVRrequesting = false;
  91259. // Are we presenting to the headset right now?
  91260. this._webVRpresenting = false;
  91261. // Are we presenting in the fullscreen fallback?
  91262. this._fullscreenVRpresenting = false;
  91263. /**
  91264. * Observable raised when entering VR.
  91265. */
  91266. this.onEnteringVRObservable = new BABYLON.Observable();
  91267. /**
  91268. * Observable raised when exiting VR.
  91269. */
  91270. this.onExitingVRObservable = new BABYLON.Observable();
  91271. /**
  91272. * Observable raised when controller mesh is loaded.
  91273. */
  91274. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91275. this._useCustomVRButton = false;
  91276. this._teleportationRequested = false;
  91277. this._teleportActive = false;
  91278. this._floorMeshesCollection = [];
  91279. this._rotationAllowed = true;
  91280. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91281. this._isDefaultTeleportationTarget = true;
  91282. this._teleportationFillColor = "#444444";
  91283. this._teleportationBorderColor = "#FFFFFF";
  91284. this._rotationAngle = 0;
  91285. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91286. this._padSensibilityUp = 0.65;
  91287. this._padSensibilityDown = 0.35;
  91288. this.leftController = null;
  91289. this.rightController = null;
  91290. /**
  91291. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91292. */
  91293. this.onNewMeshSelected = new BABYLON.Observable();
  91294. /**
  91295. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91296. */
  91297. this.onNewMeshPicked = new BABYLON.Observable();
  91298. /**
  91299. * Observable raised before camera teleportation
  91300. */
  91301. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91302. /**
  91303. * Observable raised after camera teleportation
  91304. */
  91305. this.onAfterCameraTeleport = new BABYLON.Observable();
  91306. /**
  91307. * Observable raised when current selected mesh gets unselected
  91308. */
  91309. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91310. /**
  91311. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91312. */
  91313. this.teleportationEnabled = true;
  91314. this._teleportationInitialized = false;
  91315. this._interactionsEnabled = false;
  91316. this._interactionsRequested = false;
  91317. this._displayGaze = true;
  91318. this._displayLaserPointer = true;
  91319. this._onResize = function () {
  91320. _this.moveButtonToBottomRight();
  91321. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91322. _this.exitVR();
  91323. }
  91324. };
  91325. this._onFullscreenChange = function () {
  91326. if (document.fullscreen !== undefined) {
  91327. _this._fullscreenVRpresenting = document.fullscreen;
  91328. }
  91329. else if (document.mozFullScreen !== undefined) {
  91330. _this._fullscreenVRpresenting = document.mozFullScreen;
  91331. }
  91332. else if (document.webkitIsFullScreen !== undefined) {
  91333. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91334. }
  91335. else if (document.msIsFullScreen !== undefined) {
  91336. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91337. }
  91338. else if (document.msFullscreenElement !== undefined) {
  91339. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91340. }
  91341. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91342. _this.exitVR();
  91343. if (!_this._useCustomVRButton) {
  91344. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91345. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91346. }
  91347. }
  91348. };
  91349. this.beforeRender = function () {
  91350. if (_this.leftController && _this.leftController._activePointer) {
  91351. _this._castRayAndSelectObject(_this.leftController);
  91352. }
  91353. if (_this.rightController && _this.rightController._activePointer) {
  91354. _this._castRayAndSelectObject(_this.rightController);
  91355. }
  91356. if (_this._noControllerIsActive) {
  91357. _this._castRayAndSelectObject(_this._cameraGazer);
  91358. }
  91359. else {
  91360. _this._cameraGazer._gazeTracker.isVisible = false;
  91361. }
  91362. };
  91363. this._onNewGamepadConnected = function (gamepad) {
  91364. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91365. if (gamepad.leftStick) {
  91366. gamepad.onleftstickchanged(function (stickValues) {
  91367. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91368. // Listening to classic/xbox gamepad only if no VR controller is active
  91369. if ((!_this.leftController && !_this.rightController) ||
  91370. ((_this.leftController && !_this.leftController._activePointer) &&
  91371. (_this.rightController && !_this.rightController._activePointer))) {
  91372. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91373. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91374. }
  91375. }
  91376. });
  91377. }
  91378. if (gamepad.rightStick) {
  91379. gamepad.onrightstickchanged(function (stickValues) {
  91380. if (_this._teleportationInitialized) {
  91381. _this._checkRotate(stickValues, _this._cameraGazer);
  91382. }
  91383. });
  91384. }
  91385. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91386. gamepad.onbuttondown(function (buttonPressed) {
  91387. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91388. _this._cameraGazer._selectionPointerDown();
  91389. }
  91390. });
  91391. gamepad.onbuttonup(function (buttonPressed) {
  91392. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  91393. _this._cameraGazer._selectionPointerUp();
  91394. }
  91395. });
  91396. }
  91397. }
  91398. else {
  91399. var webVRController = gamepad;
  91400. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  91401. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  91402. _this.rightController = controller;
  91403. }
  91404. else {
  91405. _this.leftController = controller;
  91406. }
  91407. _this._tryEnableInteractionOnController(controller);
  91408. }
  91409. };
  91410. // 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
  91411. this._tryEnableInteractionOnController = function (controller) {
  91412. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  91413. _this._enableInteractionOnController(controller);
  91414. }
  91415. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  91416. _this._enableTeleportationOnController(controller);
  91417. }
  91418. };
  91419. this._onNewGamepadDisconnected = function (gamepad) {
  91420. if (gamepad instanceof BABYLON.WebVRController) {
  91421. if (gamepad.hand === "left" && _this.leftController != null) {
  91422. _this.leftController.dispose();
  91423. _this.leftController = null;
  91424. }
  91425. if (gamepad.hand === "right" && _this.rightController != null) {
  91426. _this.rightController.dispose();
  91427. _this.rightController = null;
  91428. }
  91429. }
  91430. };
  91431. this._workingVector = BABYLON.Vector3.Zero();
  91432. this._workingQuaternion = BABYLON.Quaternion.Identity();
  91433. this._workingMatrix = BABYLON.Matrix.Identity();
  91434. this._scene = scene;
  91435. this._canvas = scene.getEngine().getRenderingCanvas();
  91436. // Parse options
  91437. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  91438. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  91439. }
  91440. if (webVROptions.createDeviceOrientationCamera === undefined) {
  91441. webVROptions.createDeviceOrientationCamera = true;
  91442. }
  91443. if (webVROptions.laserToggle === undefined) {
  91444. webVROptions.laserToggle = true;
  91445. }
  91446. if (webVROptions.defaultHeight === undefined) {
  91447. webVROptions.defaultHeight = 1.7;
  91448. }
  91449. if (webVROptions.useCustomVRButton) {
  91450. this._useCustomVRButton = true;
  91451. if (webVROptions.customVRButton) {
  91452. this._btnVR = webVROptions.customVRButton;
  91453. }
  91454. }
  91455. if (webVROptions.rayLength) {
  91456. this._rayLength = webVROptions.rayLength;
  91457. }
  91458. this._defaultHeight = webVROptions.defaultHeight;
  91459. if (webVROptions.positionScale) {
  91460. this._rayLength *= webVROptions.positionScale;
  91461. this._defaultHeight *= webVROptions.positionScale;
  91462. }
  91463. // Set position
  91464. if (this._scene.activeCamera) {
  91465. this._position = this._scene.activeCamera.position.clone();
  91466. }
  91467. else {
  91468. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  91469. }
  91470. // Set non-vr camera
  91471. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  91472. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  91473. // Copy data from existing camera
  91474. if (this._scene.activeCamera) {
  91475. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91476. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  91477. // Set rotation from previous camera
  91478. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  91479. var targetCamera = this._scene.activeCamera;
  91480. if (targetCamera.rotationQuaternion) {
  91481. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  91482. }
  91483. else {
  91484. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  91485. }
  91486. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  91487. }
  91488. }
  91489. this._scene.activeCamera = this._deviceOrientationCamera;
  91490. if (this._canvas) {
  91491. this._scene.activeCamera.attachControl(this._canvas);
  91492. }
  91493. }
  91494. else {
  91495. this._existingCamera = this._scene.activeCamera;
  91496. }
  91497. // Create VR cameras
  91498. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91499. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  91500. }
  91501. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  91502. this._webVRCamera.useStandingMatrix();
  91503. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  91504. // Create default button
  91505. if (!this._useCustomVRButton) {
  91506. this._btnVR = document.createElement("BUTTON");
  91507. this._btnVR.className = "babylonVRicon";
  91508. this._btnVR.id = "babylonVRiconbtn";
  91509. this._btnVR.title = "Click to switch to VR";
  91510. 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) }";
  91511. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  91512. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  91513. // css += ".babylonVRicon.vrdisplaysupported { }";
  91514. // css += ".babylonVRicon.vrdisplayready { }";
  91515. // css += ".babylonVRicon.vrdisplayrequesting { }";
  91516. var style = document.createElement('style');
  91517. style.appendChild(document.createTextNode(css));
  91518. document.getElementsByTagName('head')[0].appendChild(style);
  91519. this.moveButtonToBottomRight();
  91520. }
  91521. // VR button click event
  91522. if (this._btnVR) {
  91523. this._btnVR.addEventListener("click", function () {
  91524. if (!_this.isInVRMode) {
  91525. _this.enterVR();
  91526. }
  91527. else {
  91528. _this.exitVR();
  91529. }
  91530. });
  91531. }
  91532. // Window events
  91533. window.addEventListener("resize", this._onResize);
  91534. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  91535. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  91536. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  91537. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  91538. document.onmsfullscreenchange = this._onFullscreenChange;
  91539. // Display vr button when headset is connected
  91540. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  91541. this.displayVRButton();
  91542. }
  91543. else {
  91544. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  91545. if (e.vrDisplay) {
  91546. _this.displayVRButton();
  91547. }
  91548. });
  91549. }
  91550. // Exiting VR mode using 'ESC' key on desktop
  91551. this._onKeyDown = function (event) {
  91552. if (event.keyCode === 27 && _this.isInVRMode) {
  91553. _this.exitVR();
  91554. }
  91555. };
  91556. document.addEventListener("keydown", this._onKeyDown);
  91557. // Exiting VR mode double tapping the touch screen
  91558. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  91559. if (_this.isInVRMode) {
  91560. _this.exitVR();
  91561. if (_this._fullscreenVRpresenting) {
  91562. _this._scene.getEngine().switchFullscreen(true);
  91563. }
  91564. }
  91565. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  91566. // Listen for WebVR display changes
  91567. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  91568. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  91569. this._onVRRequestPresentStart = function () {
  91570. _this._webVRrequesting = true;
  91571. _this.updateButtonVisibility();
  91572. };
  91573. this._onVRRequestPresentComplete = function (success) {
  91574. _this._webVRrequesting = false;
  91575. _this.updateButtonVisibility();
  91576. };
  91577. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  91578. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  91579. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  91580. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  91581. scene.onDisposeObservable.add(function () {
  91582. _this.dispose();
  91583. });
  91584. // Gamepad connection events
  91585. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  91586. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  91587. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  91588. this.updateButtonVisibility();
  91589. //create easing functions
  91590. this._circleEase = new BABYLON.CircleEase();
  91591. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  91592. if (this.webVROptions.floorMeshes) {
  91593. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  91594. }
  91595. }
  91596. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  91597. /** Return this.onEnteringVRObservable
  91598. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  91599. */
  91600. get: function () {
  91601. return this.onEnteringVRObservable;
  91602. },
  91603. enumerable: true,
  91604. configurable: true
  91605. });
  91606. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  91607. /** Return this.onExitingVRObservable
  91608. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  91609. */
  91610. get: function () {
  91611. return this.onExitingVRObservable;
  91612. },
  91613. enumerable: true,
  91614. configurable: true
  91615. });
  91616. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  91617. /** Return this.onControllerMeshLoadedObservable
  91618. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  91619. */
  91620. get: function () {
  91621. return this.onControllerMeshLoadedObservable;
  91622. },
  91623. enumerable: true,
  91624. configurable: true
  91625. });
  91626. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  91627. /**
  91628. * The mesh used to display where the user is going to teleport.
  91629. */
  91630. get: function () {
  91631. return this._teleportationTarget;
  91632. },
  91633. /**
  91634. * Sets the mesh to be used to display where the user is going to teleport.
  91635. */
  91636. set: function (value) {
  91637. if (value) {
  91638. value.name = "teleportationTarget";
  91639. this._isDefaultTeleportationTarget = false;
  91640. this._teleportationTarget = value;
  91641. }
  91642. },
  91643. enumerable: true,
  91644. configurable: true
  91645. });
  91646. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  91647. /**
  91648. * The mesh used to display where the user is selecting,
  91649. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  91650. * See http://doc.babylonjs.com/resources/baking_transformations
  91651. */
  91652. get: function () {
  91653. return this._cameraGazer._gazeTracker;
  91654. },
  91655. set: function (value) {
  91656. if (value) {
  91657. this._cameraGazer._gazeTracker = value;
  91658. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  91659. this._cameraGazer._gazeTracker.isPickable = false;
  91660. this._cameraGazer._gazeTracker.isVisible = false;
  91661. this._cameraGazer._gazeTracker.name = "gazeTracker";
  91662. if (this.leftController) {
  91663. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91664. }
  91665. if (this.rightController) {
  91666. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  91667. }
  91668. }
  91669. },
  91670. enumerable: true,
  91671. configurable: true
  91672. });
  91673. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  91674. /**
  91675. * If the ray of the gaze should be displayed.
  91676. */
  91677. get: function () {
  91678. return this._displayGaze;
  91679. },
  91680. /**
  91681. * Sets if the ray of the gaze should be displayed.
  91682. */
  91683. set: function (value) {
  91684. this._displayGaze = value;
  91685. if (!value) {
  91686. this._cameraGazer._gazeTracker.isVisible = false;
  91687. if (this.leftController) {
  91688. this.leftController._gazeTracker.isVisible = false;
  91689. }
  91690. if (this.rightController) {
  91691. this.rightController._gazeTracker.isVisible = false;
  91692. }
  91693. }
  91694. },
  91695. enumerable: true,
  91696. configurable: true
  91697. });
  91698. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  91699. /**
  91700. * If the ray of the LaserPointer should be displayed.
  91701. */
  91702. get: function () {
  91703. return this._displayLaserPointer;
  91704. },
  91705. /**
  91706. * Sets if the ray of the LaserPointer should be displayed.
  91707. */
  91708. set: function (value) {
  91709. this._displayLaserPointer = value;
  91710. if (!value) {
  91711. if (this.rightController) {
  91712. this.rightController._deactivatePointer();
  91713. this.rightController._gazeTracker.isVisible = false;
  91714. }
  91715. if (this.leftController) {
  91716. this.leftController._deactivatePointer();
  91717. this.leftController._gazeTracker.isVisible = false;
  91718. }
  91719. }
  91720. else {
  91721. if (this.rightController) {
  91722. this.rightController._activatePointer();
  91723. }
  91724. if (this.leftController) {
  91725. this.leftController._activatePointer();
  91726. }
  91727. }
  91728. },
  91729. enumerable: true,
  91730. configurable: true
  91731. });
  91732. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  91733. /**
  91734. * The deviceOrientationCamera used as the camera when not in VR.
  91735. */
  91736. get: function () {
  91737. return this._deviceOrientationCamera;
  91738. },
  91739. enumerable: true,
  91740. configurable: true
  91741. });
  91742. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  91743. /**
  91744. * Based on the current WebVR support, returns the current VR camera used.
  91745. */
  91746. get: function () {
  91747. if (this._webVRready) {
  91748. return this._webVRCamera;
  91749. }
  91750. else {
  91751. return this._scene.activeCamera;
  91752. }
  91753. },
  91754. enumerable: true,
  91755. configurable: true
  91756. });
  91757. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  91758. /**
  91759. * The webVRCamera which is used when in VR.
  91760. */
  91761. get: function () {
  91762. return this._webVRCamera;
  91763. },
  91764. enumerable: true,
  91765. configurable: true
  91766. });
  91767. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  91768. /**
  91769. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  91770. */
  91771. get: function () {
  91772. return this._vrDeviceOrientationCamera;
  91773. },
  91774. enumerable: true,
  91775. configurable: true
  91776. });
  91777. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  91778. get: function () {
  91779. var result = this._cameraGazer._teleportationRequestInitiated
  91780. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  91781. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  91782. return result;
  91783. },
  91784. enumerable: true,
  91785. configurable: true
  91786. });
  91787. // Raised when one of the controller has loaded successfully its associated default mesh
  91788. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  91789. if (this.leftController && this.leftController.webVRController == webVRController) {
  91790. if (webVRController.mesh) {
  91791. this.leftController._setLaserPointerParent(webVRController.mesh);
  91792. }
  91793. }
  91794. if (this.rightController && this.rightController.webVRController == webVRController) {
  91795. if (webVRController.mesh) {
  91796. this.rightController._setLaserPointerParent(webVRController.mesh);
  91797. }
  91798. }
  91799. try {
  91800. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  91801. }
  91802. catch (err) {
  91803. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  91804. }
  91805. };
  91806. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  91807. /**
  91808. * Gets a value indicating if we are currently in VR mode.
  91809. */
  91810. get: function () {
  91811. return this._webVRpresenting || this._fullscreenVRpresenting;
  91812. },
  91813. enumerable: true,
  91814. configurable: true
  91815. });
  91816. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  91817. var vrDisplay = this._scene.getEngine().getVRDevice();
  91818. if (vrDisplay) {
  91819. var wasPresenting = this._webVRpresenting;
  91820. // A VR display is connected
  91821. this._webVRpresenting = vrDisplay.isPresenting;
  91822. if (wasPresenting && !this._webVRpresenting)
  91823. this.exitVR();
  91824. }
  91825. else {
  91826. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  91827. }
  91828. this.updateButtonVisibility();
  91829. };
  91830. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  91831. this._webVRsupported = eventArgs.vrSupported;
  91832. this._webVRready = !!eventArgs.vrDisplay;
  91833. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  91834. this.updateButtonVisibility();
  91835. };
  91836. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  91837. if (this._canvas && !this._useCustomVRButton) {
  91838. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  91839. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  91840. }
  91841. };
  91842. VRExperienceHelper.prototype.displayVRButton = function () {
  91843. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  91844. document.body.appendChild(this._btnVR);
  91845. this._btnVRDisplayed = true;
  91846. }
  91847. };
  91848. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  91849. if (!this._btnVR || this._useCustomVRButton) {
  91850. return;
  91851. }
  91852. this._btnVR.className = "babylonVRicon";
  91853. if (this.isInVRMode) {
  91854. this._btnVR.className += " vrdisplaypresenting";
  91855. }
  91856. else {
  91857. if (this._webVRready)
  91858. this._btnVR.className += " vrdisplayready";
  91859. if (this._webVRsupported)
  91860. this._btnVR.className += " vrdisplaysupported";
  91861. if (this._webVRrequesting)
  91862. this._btnVR.className += " vrdisplayrequesting";
  91863. }
  91864. };
  91865. /**
  91866. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  91867. * Otherwise, will use the fullscreen API.
  91868. */
  91869. VRExperienceHelper.prototype.enterVR = function () {
  91870. if (this.onEnteringVRObservable) {
  91871. try {
  91872. this.onEnteringVRObservable.notifyObservers(this);
  91873. }
  91874. catch (err) {
  91875. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  91876. }
  91877. }
  91878. if (this._scene.activeCamera) {
  91879. this._position = this._scene.activeCamera.position.clone();
  91880. // make sure that we return to the last active camera
  91881. this._existingCamera = this._scene.activeCamera;
  91882. }
  91883. if (this._webVRrequesting)
  91884. return;
  91885. // If WebVR is supported and a headset is connected
  91886. if (this._webVRready) {
  91887. if (!this._webVRpresenting) {
  91888. this._webVRCamera.position = this._position;
  91889. this._scene.activeCamera = this._webVRCamera;
  91890. }
  91891. }
  91892. else if (this._vrDeviceOrientationCamera) {
  91893. this._vrDeviceOrientationCamera.position = this._position;
  91894. if (this._scene.activeCamera) {
  91895. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  91896. }
  91897. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  91898. this._scene.getEngine().switchFullscreen(true);
  91899. this.updateButtonVisibility();
  91900. }
  91901. if (this._scene.activeCamera && this._canvas) {
  91902. this._scene.activeCamera.attachControl(this._canvas);
  91903. }
  91904. if (this._interactionsEnabled) {
  91905. this._scene.registerBeforeRender(this.beforeRender);
  91906. }
  91907. };
  91908. /**
  91909. * Attempt to exit VR, or fullscreen.
  91910. */
  91911. VRExperienceHelper.prototype.exitVR = function () {
  91912. if (this.onExitingVRObservable) {
  91913. try {
  91914. this.onExitingVRObservable.notifyObservers(this);
  91915. }
  91916. catch (err) {
  91917. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  91918. }
  91919. }
  91920. if (this._webVRpresenting) {
  91921. this._scene.getEngine().disableVR();
  91922. }
  91923. if (this._scene.activeCamera) {
  91924. this._position = this._scene.activeCamera.position.clone();
  91925. }
  91926. if (this._deviceOrientationCamera) {
  91927. this._deviceOrientationCamera.position = this._position;
  91928. this._scene.activeCamera = this._deviceOrientationCamera;
  91929. if (this._canvas) {
  91930. this._scene.activeCamera.attachControl(this._canvas);
  91931. }
  91932. }
  91933. else if (this._existingCamera) {
  91934. this._existingCamera.position = this._position;
  91935. this._scene.activeCamera = this._existingCamera;
  91936. }
  91937. this.updateButtonVisibility();
  91938. if (this._interactionsEnabled) {
  91939. this._scene.unregisterBeforeRender(this.beforeRender);
  91940. }
  91941. // resize to update width and height when exiting vr exits fullscreen
  91942. this._scene.getEngine().resize();
  91943. };
  91944. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  91945. /**
  91946. * The position of the vr experience helper.
  91947. */
  91948. get: function () {
  91949. return this._position;
  91950. },
  91951. /**
  91952. * Sets the position of the vr experience helper.
  91953. */
  91954. set: function (value) {
  91955. this._position = value;
  91956. if (this._scene.activeCamera) {
  91957. this._scene.activeCamera.position = value;
  91958. }
  91959. },
  91960. enumerable: true,
  91961. configurable: true
  91962. });
  91963. /**
  91964. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  91965. */
  91966. VRExperienceHelper.prototype.enableInteractions = function () {
  91967. var _this = this;
  91968. if (!this._interactionsEnabled) {
  91969. this._interactionsRequested = true;
  91970. if (this.leftController) {
  91971. this._enableInteractionOnController(this.leftController);
  91972. }
  91973. if (this.rightController) {
  91974. this._enableInteractionOnController(this.rightController);
  91975. }
  91976. this.raySelectionPredicate = function (mesh) {
  91977. return mesh.isVisible;
  91978. };
  91979. this.meshSelectionPredicate = function (mesh) {
  91980. return true;
  91981. };
  91982. this._raySelectionPredicate = function (mesh) {
  91983. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  91984. && mesh.name.indexOf("teleportationTarget") === -1
  91985. && mesh.name.indexOf("torusTeleportation") === -1
  91986. && mesh.name.indexOf("laserPointer") === -1)) {
  91987. return _this.raySelectionPredicate(mesh);
  91988. }
  91989. return false;
  91990. };
  91991. this._interactionsEnabled = true;
  91992. }
  91993. };
  91994. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  91995. get: function () {
  91996. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  91997. },
  91998. enumerable: true,
  91999. configurable: true
  92000. });
  92001. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92002. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92003. if (this._floorMeshesCollection[i].id === mesh.id) {
  92004. return true;
  92005. }
  92006. }
  92007. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92008. return true;
  92009. }
  92010. return false;
  92011. };
  92012. /**
  92013. * Adds a floor mesh to be used for teleportation.
  92014. * @param floorMesh the mesh to be used for teleportation.
  92015. */
  92016. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92017. if (!this._floorMeshesCollection) {
  92018. return;
  92019. }
  92020. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92021. return;
  92022. }
  92023. this._floorMeshesCollection.push(floorMesh);
  92024. };
  92025. /**
  92026. * Removes a floor mesh from being used for teleportation.
  92027. * @param floorMesh the mesh to be removed.
  92028. */
  92029. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92030. if (!this._floorMeshesCollection) {
  92031. return;
  92032. }
  92033. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92034. if (meshIndex !== -1) {
  92035. this._floorMeshesCollection.splice(meshIndex, 1);
  92036. }
  92037. };
  92038. /**
  92039. * Enables interactions and teleportation using the VR controllers and gaze.
  92040. * @param vrTeleportationOptions options to modify teleportation behavior.
  92041. */
  92042. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92043. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92044. if (!this._teleportationInitialized) {
  92045. this._teleportationRequested = true;
  92046. this.enableInteractions();
  92047. if (vrTeleportationOptions.floorMeshName) {
  92048. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92049. }
  92050. if (vrTeleportationOptions.floorMeshes) {
  92051. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92052. }
  92053. if (this.leftController != null) {
  92054. this._enableTeleportationOnController(this.leftController);
  92055. }
  92056. if (this.rightController != null) {
  92057. this._enableTeleportationOnController(this.rightController);
  92058. }
  92059. // Creates an image processing post process for the vignette not relying
  92060. // on the main scene configuration for image processing to reduce setup and spaces
  92061. // (gamma/linear) conflicts.
  92062. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92063. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92064. imageProcessingConfiguration.vignetteEnabled = true;
  92065. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92066. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92067. this._teleportationInitialized = true;
  92068. if (this._isDefaultTeleportationTarget) {
  92069. this._createTeleportationCircles();
  92070. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92071. }
  92072. }
  92073. };
  92074. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92075. var _this = this;
  92076. var controllerMesh = controller.webVRController.mesh;
  92077. if (controllerMesh) {
  92078. controller._interactionsEnabled = true;
  92079. controller._activatePointer();
  92080. if (this.webVROptions.laserToggle) {
  92081. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92082. // Enabling / disabling laserPointer
  92083. if (_this._displayLaserPointer && stateObject.value === 1) {
  92084. if (controller._activePointer) {
  92085. controller._deactivatePointer();
  92086. }
  92087. else {
  92088. controller._activatePointer();
  92089. }
  92090. if (_this.displayGaze) {
  92091. controller._gazeTracker.isVisible = controller._activePointer;
  92092. }
  92093. }
  92094. });
  92095. }
  92096. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92097. var gazer = controller;
  92098. if (_this._noControllerIsActive) {
  92099. gazer = _this._cameraGazer;
  92100. }
  92101. if (!gazer._pointerDownOnMeshAsked) {
  92102. if (stateObject.value > _this._padSensibilityUp) {
  92103. gazer._selectionPointerDown();
  92104. }
  92105. }
  92106. else if (stateObject.value < _this._padSensibilityDown) {
  92107. gazer._selectionPointerUp();
  92108. }
  92109. });
  92110. }
  92111. };
  92112. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92113. // Dont teleport if another gaze already requested teleportation
  92114. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92115. return;
  92116. }
  92117. if (!gazer._teleportationRequestInitiated) {
  92118. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92119. gazer._activatePointer();
  92120. gazer._teleportationRequestInitiated = true;
  92121. }
  92122. }
  92123. else {
  92124. // Listening to the proper controller values changes to confirm teleportation
  92125. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92126. if (this._teleportActive) {
  92127. this._teleportCamera(this._haloCenter);
  92128. }
  92129. gazer._teleportationRequestInitiated = false;
  92130. }
  92131. }
  92132. };
  92133. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92134. // Only rotate when user is not currently selecting a teleportation location
  92135. if (gazer._teleportationRequestInitiated) {
  92136. return;
  92137. }
  92138. if (!gazer._rotationLeftAsked) {
  92139. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92140. gazer._rotationLeftAsked = true;
  92141. if (this._rotationAllowed) {
  92142. this._rotateCamera(false);
  92143. }
  92144. }
  92145. }
  92146. else {
  92147. if (stateObject.x > -this._padSensibilityDown) {
  92148. gazer._rotationLeftAsked = false;
  92149. }
  92150. }
  92151. if (!gazer._rotationRightAsked) {
  92152. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92153. gazer._rotationRightAsked = true;
  92154. if (this._rotationAllowed) {
  92155. this._rotateCamera(true);
  92156. }
  92157. }
  92158. }
  92159. else {
  92160. if (stateObject.x < this._padSensibilityDown) {
  92161. gazer._rotationRightAsked = false;
  92162. }
  92163. }
  92164. };
  92165. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92166. // Only teleport backwards when user is not currently selecting a teleportation location
  92167. if (gazer._teleportationRequestInitiated) {
  92168. return;
  92169. }
  92170. // Teleport backwards
  92171. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92172. if (!gazer._teleportationBackRequestInitiated) {
  92173. if (!this.currentVRCamera) {
  92174. return;
  92175. }
  92176. // Get rotation and position of the current camera
  92177. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92178. var position = this.currentVRCamera.position;
  92179. // If the camera has device position, use that instead
  92180. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92181. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92182. position = this.currentVRCamera.devicePosition;
  92183. }
  92184. // Get matrix with only the y rotation of the device rotation
  92185. rotation.toEulerAnglesToRef(this._workingVector);
  92186. this._workingVector.z = 0;
  92187. this._workingVector.x = 0;
  92188. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92189. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92190. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92191. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92192. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92193. var ray = new BABYLON.Ray(position, this._workingVector);
  92194. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92195. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92196. this._teleportCamera(hit.pickedPoint);
  92197. }
  92198. gazer._teleportationBackRequestInitiated = true;
  92199. }
  92200. }
  92201. else {
  92202. gazer._teleportationBackRequestInitiated = false;
  92203. }
  92204. };
  92205. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92206. var _this = this;
  92207. var controllerMesh = controller.webVRController.mesh;
  92208. if (controllerMesh) {
  92209. if (!controller._interactionsEnabled) {
  92210. this._enableInteractionOnController(controller);
  92211. }
  92212. controller._interactionsEnabled = true;
  92213. controller._teleportationEnabled = true;
  92214. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92215. controller._dpadPressed = false;
  92216. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92217. controller._dpadPressed = stateObject.pressed;
  92218. if (!controller._dpadPressed) {
  92219. controller._rotationLeftAsked = false;
  92220. controller._rotationRightAsked = false;
  92221. controller._teleportationBackRequestInitiated = false;
  92222. }
  92223. });
  92224. }
  92225. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92226. if (_this.teleportationEnabled) {
  92227. _this._checkTeleportBackwards(stateObject, controller);
  92228. _this._checkTeleportWithRay(stateObject, controller);
  92229. }
  92230. _this._checkRotate(stateObject, controller);
  92231. });
  92232. }
  92233. };
  92234. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92235. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92236. this._teleportationTarget.isPickable = false;
  92237. var length = 512;
  92238. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92239. dynamicTexture.hasAlpha = true;
  92240. var context = dynamicTexture.getContext();
  92241. var centerX = length / 2;
  92242. var centerY = length / 2;
  92243. var radius = 200;
  92244. context.beginPath();
  92245. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92246. context.fillStyle = this._teleportationFillColor;
  92247. context.fill();
  92248. context.lineWidth = 10;
  92249. context.strokeStyle = this._teleportationBorderColor;
  92250. context.stroke();
  92251. context.closePath();
  92252. dynamicTexture.update();
  92253. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92254. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92255. this._teleportationTarget.material = teleportationCircleMaterial;
  92256. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92257. torus.isPickable = false;
  92258. torus.parent = this._teleportationTarget;
  92259. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92260. var keys = [];
  92261. keys.push({
  92262. frame: 0,
  92263. value: 0
  92264. });
  92265. keys.push({
  92266. frame: 30,
  92267. value: 0.4
  92268. });
  92269. keys.push({
  92270. frame: 60,
  92271. value: 0
  92272. });
  92273. animationInnerCircle.setKeys(keys);
  92274. var easingFunction = new BABYLON.SineEase();
  92275. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92276. animationInnerCircle.setEasingFunction(easingFunction);
  92277. torus.animations = [];
  92278. torus.animations.push(animationInnerCircle);
  92279. this._scene.beginAnimation(torus, 0, 60, true);
  92280. this._hideTeleportationTarget();
  92281. };
  92282. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92283. this._teleportActive = true;
  92284. if (this._teleportationInitialized) {
  92285. this._teleportationTarget.isVisible = true;
  92286. if (this._isDefaultTeleportationTarget) {
  92287. this._teleportationTarget.getChildren()[0].isVisible = true;
  92288. }
  92289. }
  92290. };
  92291. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92292. this._teleportActive = false;
  92293. if (this._teleportationInitialized) {
  92294. this._teleportationTarget.isVisible = false;
  92295. if (this._isDefaultTeleportationTarget) {
  92296. this._teleportationTarget.getChildren()[0].isVisible = false;
  92297. }
  92298. }
  92299. };
  92300. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92301. var _this = this;
  92302. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92303. return;
  92304. }
  92305. if (right) {
  92306. this._rotationAngle++;
  92307. }
  92308. else {
  92309. this._rotationAngle--;
  92310. }
  92311. this.currentVRCamera.animations = [];
  92312. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92313. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92314. var animationRotationKeys = [];
  92315. animationRotationKeys.push({
  92316. frame: 0,
  92317. value: this.currentVRCamera.rotationQuaternion
  92318. });
  92319. animationRotationKeys.push({
  92320. frame: 6,
  92321. value: target
  92322. });
  92323. animationRotation.setKeys(animationRotationKeys);
  92324. animationRotation.setEasingFunction(this._circleEase);
  92325. this.currentVRCamera.animations.push(animationRotation);
  92326. this._postProcessMove.animations = [];
  92327. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92328. var vignetteWeightKeys = [];
  92329. vignetteWeightKeys.push({
  92330. frame: 0,
  92331. value: 0
  92332. });
  92333. vignetteWeightKeys.push({
  92334. frame: 3,
  92335. value: 4
  92336. });
  92337. vignetteWeightKeys.push({
  92338. frame: 6,
  92339. value: 0
  92340. });
  92341. animationPP.setKeys(vignetteWeightKeys);
  92342. animationPP.setEasingFunction(this._circleEase);
  92343. this._postProcessMove.animations.push(animationPP);
  92344. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92345. var vignetteStretchKeys = [];
  92346. vignetteStretchKeys.push({
  92347. frame: 0,
  92348. value: 0
  92349. });
  92350. vignetteStretchKeys.push({
  92351. frame: 3,
  92352. value: 10
  92353. });
  92354. vignetteStretchKeys.push({
  92355. frame: 6,
  92356. value: 0
  92357. });
  92358. animationPP2.setKeys(vignetteStretchKeys);
  92359. animationPP2.setEasingFunction(this._circleEase);
  92360. this._postProcessMove.animations.push(animationPP2);
  92361. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92362. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92363. this._postProcessMove.samples = 4;
  92364. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92365. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92366. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92367. });
  92368. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92369. };
  92370. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92371. if (hit.pickedPoint) {
  92372. if (gazer._teleportationRequestInitiated) {
  92373. this._displayTeleportationTarget();
  92374. this._haloCenter.copyFrom(hit.pickedPoint);
  92375. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92376. }
  92377. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92378. if (pickNormal) {
  92379. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92380. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92381. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92382. }
  92383. this._teleportationTarget.position.y += 0.1;
  92384. }
  92385. };
  92386. VRExperienceHelper.prototype._teleportCamera = function (location) {
  92387. var _this = this;
  92388. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92389. return;
  92390. }
  92391. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  92392. // offset of the headset from the anchor.
  92393. if (this.webVRCamera.leftCamera) {
  92394. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  92395. this._workingVector.subtractInPlace(this.webVRCamera.position);
  92396. location.subtractToRef(this._workingVector, this._workingVector);
  92397. }
  92398. else {
  92399. this._workingVector.copyFrom(location);
  92400. }
  92401. // Add height to account for user's height offset
  92402. if (this.isInVRMode) {
  92403. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  92404. }
  92405. else {
  92406. this._workingVector.y += this._defaultHeight;
  92407. }
  92408. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  92409. // Create animation from the camera's position to the new location
  92410. this.currentVRCamera.animations = [];
  92411. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92412. var animationCameraTeleportationKeys = [{
  92413. frame: 0,
  92414. value: this.currentVRCamera.position
  92415. },
  92416. {
  92417. frame: 11,
  92418. value: this._workingVector
  92419. }
  92420. ];
  92421. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  92422. animationCameraTeleportation.setEasingFunction(this._circleEase);
  92423. this.currentVRCamera.animations.push(animationCameraTeleportation);
  92424. this._postProcessMove.animations = [];
  92425. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92426. var vignetteWeightKeys = [];
  92427. vignetteWeightKeys.push({
  92428. frame: 0,
  92429. value: 0
  92430. });
  92431. vignetteWeightKeys.push({
  92432. frame: 5,
  92433. value: 8
  92434. });
  92435. vignetteWeightKeys.push({
  92436. frame: 11,
  92437. value: 0
  92438. });
  92439. animationPP.setKeys(vignetteWeightKeys);
  92440. this._postProcessMove.animations.push(animationPP);
  92441. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92442. var vignetteStretchKeys = [];
  92443. vignetteStretchKeys.push({
  92444. frame: 0,
  92445. value: 0
  92446. });
  92447. vignetteStretchKeys.push({
  92448. frame: 5,
  92449. value: 10
  92450. });
  92451. vignetteStretchKeys.push({
  92452. frame: 11,
  92453. value: 0
  92454. });
  92455. animationPP2.setKeys(vignetteStretchKeys);
  92456. this._postProcessMove.animations.push(animationPP2);
  92457. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92458. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92459. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92460. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  92461. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92462. });
  92463. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  92464. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  92465. });
  92466. this._hideTeleportationTarget();
  92467. };
  92468. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  92469. if (normal) {
  92470. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  92471. if (angle < Math.PI / 2) {
  92472. normal.scaleInPlace(-1);
  92473. }
  92474. }
  92475. return normal;
  92476. };
  92477. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  92478. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92479. return;
  92480. }
  92481. var ray = gazer._getForwardRay(this._rayLength);
  92482. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92483. if (hit) {
  92484. // Populate the contrllers mesh that can be used for drag/drop
  92485. if (gazer._laserPointer) {
  92486. hit.originMesh = gazer._laserPointer.parent;
  92487. }
  92488. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  92489. }
  92490. gazer._currentHit = hit;
  92491. // Moving the gazeTracker on the mesh face targetted
  92492. if (hit && hit.pickedPoint) {
  92493. if (this._displayGaze) {
  92494. var multiplier = 1;
  92495. gazer._gazeTracker.isVisible = true;
  92496. if (gazer._isActionableMesh) {
  92497. multiplier = 3;
  92498. }
  92499. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  92500. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  92501. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  92502. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  92503. // To avoid z-fighting
  92504. var deltaFighting = 0.002;
  92505. if (pickNormal) {
  92506. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92507. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92508. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  92509. }
  92510. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  92511. if (gazer._gazeTracker.position.x < 0) {
  92512. gazer._gazeTracker.position.x += deltaFighting;
  92513. }
  92514. else {
  92515. gazer._gazeTracker.position.x -= deltaFighting;
  92516. }
  92517. if (gazer._gazeTracker.position.y < 0) {
  92518. gazer._gazeTracker.position.y += deltaFighting;
  92519. }
  92520. else {
  92521. gazer._gazeTracker.position.y -= deltaFighting;
  92522. }
  92523. if (gazer._gazeTracker.position.z < 0) {
  92524. gazer._gazeTracker.position.z += deltaFighting;
  92525. }
  92526. else {
  92527. gazer._gazeTracker.position.z -= deltaFighting;
  92528. }
  92529. }
  92530. // Changing the size of the laser pointer based on the distance from the targetted point
  92531. gazer._updatePointerDistance(hit.distance);
  92532. }
  92533. else {
  92534. gazer._updatePointerDistance();
  92535. gazer._gazeTracker.isVisible = false;
  92536. }
  92537. if (hit && hit.pickedMesh) {
  92538. // The object selected is the floor, we're in a teleportation scenario
  92539. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  92540. // Moving the teleportation area to this targetted point
  92541. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  92542. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  92543. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92544. }
  92545. gazer._currentMeshSelected = null;
  92546. if (gazer._teleportationRequestInitiated) {
  92547. this._moveTeleportationSelectorTo(hit, gazer, ray);
  92548. }
  92549. return;
  92550. }
  92551. // If not, we're in a selection scenario
  92552. //this._teleportationAllowed = false;
  92553. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  92554. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  92555. this.onNewMeshPicked.notifyObservers(hit);
  92556. gazer._currentMeshSelected = hit.pickedMesh;
  92557. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  92558. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  92559. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  92560. gazer._isActionableMesh = true;
  92561. }
  92562. else {
  92563. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92564. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92565. gazer._isActionableMesh = false;
  92566. }
  92567. try {
  92568. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  92569. }
  92570. catch (err) {
  92571. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  92572. }
  92573. }
  92574. else {
  92575. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92576. gazer._currentMeshSelected = null;
  92577. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92578. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92579. }
  92580. }
  92581. }
  92582. else {
  92583. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  92584. gazer._currentMeshSelected = null;
  92585. //this._teleportationAllowed = false;
  92586. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92587. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  92588. }
  92589. };
  92590. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  92591. if (mesh) {
  92592. this.onSelectedMeshUnselected.notifyObservers(mesh);
  92593. }
  92594. };
  92595. /**
  92596. * Sets the color of the laser ray from the vr controllers.
  92597. * @param color new color for the ray.
  92598. */
  92599. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  92600. if (this.leftController) {
  92601. this.leftController._setLaserPointerColor(color);
  92602. }
  92603. if (this.rightController) {
  92604. this.rightController._setLaserPointerColor(color);
  92605. }
  92606. };
  92607. /**
  92608. * Sets the color of the ray from the vr headsets gaze.
  92609. * @param color new color for the ray.
  92610. */
  92611. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  92612. if (!this._cameraGazer._gazeTracker.material) {
  92613. return;
  92614. }
  92615. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  92616. if (this.leftController) {
  92617. this.leftController._gazeTracker.material.emissiveColor = color;
  92618. }
  92619. if (this.rightController) {
  92620. this.rightController._gazeTracker.material.emissiveColor = color;
  92621. }
  92622. };
  92623. /**
  92624. * Exits VR and disposes of the vr experience helper
  92625. */
  92626. VRExperienceHelper.prototype.dispose = function () {
  92627. if (this.isInVRMode) {
  92628. this.exitVR();
  92629. }
  92630. if (this._postProcessMove) {
  92631. this._postProcessMove.dispose();
  92632. }
  92633. if (this._webVRCamera) {
  92634. this._webVRCamera.dispose();
  92635. }
  92636. if (this._vrDeviceOrientationCamera) {
  92637. this._vrDeviceOrientationCamera.dispose();
  92638. }
  92639. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  92640. document.body.removeChild(this._btnVR);
  92641. }
  92642. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  92643. this._deviceOrientationCamera.dispose();
  92644. }
  92645. if (this._cameraGazer) {
  92646. this._cameraGazer.dispose();
  92647. }
  92648. if (this.leftController) {
  92649. this.leftController.dispose();
  92650. }
  92651. if (this.rightController) {
  92652. this.rightController.dispose();
  92653. }
  92654. if (this._teleportationTarget) {
  92655. this._teleportationTarget.dispose();
  92656. }
  92657. this._floorMeshesCollection = [];
  92658. document.removeEventListener("keydown", this._onKeyDown);
  92659. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92660. window.removeEventListener("resize", this._onResize);
  92661. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  92662. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  92663. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  92664. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  92665. document.onmsfullscreenchange = null;
  92666. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  92667. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  92668. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  92669. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92670. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  92671. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  92672. this._scene.unregisterBeforeRender(this.beforeRender);
  92673. };
  92674. /**
  92675. * Gets the name of the VRExperienceHelper class
  92676. * @returns "VRExperienceHelper"
  92677. */
  92678. VRExperienceHelper.prototype.getClassName = function () {
  92679. return "VRExperienceHelper";
  92680. };
  92681. return VRExperienceHelper;
  92682. }());
  92683. BABYLON.VRExperienceHelper = VRExperienceHelper;
  92684. })(BABYLON || (BABYLON = {}));
  92685. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  92686. // Mainly based on these 2 articles :
  92687. // 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
  92688. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  92689. var BABYLON;
  92690. (function (BABYLON) {
  92691. /**
  92692. * Defines the potential axis of a Joystick
  92693. */
  92694. var JoystickAxis;
  92695. (function (JoystickAxis) {
  92696. /** X axis */
  92697. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  92698. /** Y axis */
  92699. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  92700. /** Z axis */
  92701. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  92702. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  92703. /**
  92704. * Class used to define virtual joystick (used in touch mode)
  92705. */
  92706. var VirtualJoystick = /** @class */ (function () {
  92707. /**
  92708. * Creates a new virtual joystick
  92709. * @param leftJoystick defines that the joystick is for left hand (false by default)
  92710. */
  92711. function VirtualJoystick(leftJoystick) {
  92712. var _this = this;
  92713. if (leftJoystick) {
  92714. this._leftJoystick = true;
  92715. }
  92716. else {
  92717. this._leftJoystick = false;
  92718. }
  92719. VirtualJoystick._globalJoystickIndex++;
  92720. // By default left & right arrow keys are moving the X
  92721. // and up & down keys are moving the Y
  92722. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92723. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92724. this.reverseLeftRight = false;
  92725. this.reverseUpDown = false;
  92726. // collections of pointers
  92727. this._touches = new BABYLON.StringDictionary();
  92728. this.deltaPosition = BABYLON.Vector3.Zero();
  92729. this._joystickSensibility = 25;
  92730. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92731. this._onResize = function (evt) {
  92732. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92733. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92734. if (VirtualJoystick.vjCanvas) {
  92735. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  92736. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  92737. }
  92738. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  92739. };
  92740. // injecting a canvas element on top of the canvas 3D game
  92741. if (!VirtualJoystick.vjCanvas) {
  92742. window.addEventListener("resize", this._onResize, false);
  92743. VirtualJoystick.vjCanvas = document.createElement("canvas");
  92744. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  92745. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  92746. VirtualJoystick.vjCanvas.width = window.innerWidth;
  92747. VirtualJoystick.vjCanvas.height = window.innerHeight;
  92748. VirtualJoystick.vjCanvas.style.width = "100%";
  92749. VirtualJoystick.vjCanvas.style.height = "100%";
  92750. VirtualJoystick.vjCanvas.style.position = "absolute";
  92751. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  92752. VirtualJoystick.vjCanvas.style.top = "0px";
  92753. VirtualJoystick.vjCanvas.style.left = "0px";
  92754. VirtualJoystick.vjCanvas.style.zIndex = "5";
  92755. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  92756. // Support for jQuery PEP polyfill
  92757. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  92758. var context = VirtualJoystick.vjCanvas.getContext('2d');
  92759. if (!context) {
  92760. throw new Error("Unable to create canvas for virtual joystick");
  92761. }
  92762. VirtualJoystick.vjCanvasContext = context;
  92763. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  92764. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92765. document.body.appendChild(VirtualJoystick.vjCanvas);
  92766. }
  92767. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  92768. this.pressed = false;
  92769. // default joystick color
  92770. this._joystickColor = "cyan";
  92771. this._joystickPointerID = -1;
  92772. // current joystick position
  92773. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  92774. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  92775. // origin joystick position
  92776. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  92777. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  92778. this._onPointerDownHandlerRef = function (evt) {
  92779. _this._onPointerDown(evt);
  92780. };
  92781. this._onPointerMoveHandlerRef = function (evt) {
  92782. _this._onPointerMove(evt);
  92783. };
  92784. this._onPointerUpHandlerRef = function (evt) {
  92785. _this._onPointerUp(evt);
  92786. };
  92787. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  92788. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  92789. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  92790. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  92791. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  92792. evt.preventDefault(); // Disables system menu
  92793. }, false);
  92794. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92795. }
  92796. /**
  92797. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  92798. * @param newJoystickSensibility defines the new sensibility
  92799. */
  92800. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  92801. this._joystickSensibility = newJoystickSensibility;
  92802. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  92803. };
  92804. VirtualJoystick.prototype._onPointerDown = function (e) {
  92805. var positionOnScreenCondition;
  92806. e.preventDefault();
  92807. if (this._leftJoystick === true) {
  92808. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  92809. }
  92810. else {
  92811. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  92812. }
  92813. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  92814. // First contact will be dedicated to the virtual joystick
  92815. this._joystickPointerID = e.pointerId;
  92816. this._joystickPointerStartPos.x = e.clientX;
  92817. this._joystickPointerStartPos.y = e.clientY;
  92818. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  92819. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  92820. this._deltaJoystickVector.x = 0;
  92821. this._deltaJoystickVector.y = 0;
  92822. this.pressed = true;
  92823. this._touches.add(e.pointerId.toString(), e);
  92824. }
  92825. else {
  92826. // You can only trigger the action buttons with a joystick declared
  92827. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  92828. this._action();
  92829. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  92830. }
  92831. }
  92832. };
  92833. VirtualJoystick.prototype._onPointerMove = function (e) {
  92834. // If the current pointer is the one associated to the joystick (first touch contact)
  92835. if (this._joystickPointerID == e.pointerId) {
  92836. this._joystickPointerPos.x = e.clientX;
  92837. this._joystickPointerPos.y = e.clientY;
  92838. this._deltaJoystickVector = this._joystickPointerPos.clone();
  92839. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  92840. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  92841. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  92842. switch (this._axisTargetedByLeftAndRight) {
  92843. case JoystickAxis.X:
  92844. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  92845. break;
  92846. case JoystickAxis.Y:
  92847. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  92848. break;
  92849. case JoystickAxis.Z:
  92850. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  92851. break;
  92852. }
  92853. var directionUpDown = this.reverseUpDown ? 1 : -1;
  92854. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  92855. switch (this._axisTargetedByUpAndDown) {
  92856. case JoystickAxis.X:
  92857. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  92858. break;
  92859. case JoystickAxis.Y:
  92860. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  92861. break;
  92862. case JoystickAxis.Z:
  92863. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  92864. break;
  92865. }
  92866. }
  92867. else {
  92868. var data = this._touches.get(e.pointerId.toString());
  92869. if (data) {
  92870. data.x = e.clientX;
  92871. data.y = e.clientY;
  92872. }
  92873. }
  92874. };
  92875. VirtualJoystick.prototype._onPointerUp = function (e) {
  92876. if (this._joystickPointerID == e.pointerId) {
  92877. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  92878. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  92879. this._joystickPointerID = -1;
  92880. this.pressed = false;
  92881. }
  92882. else {
  92883. var touch = this._touches.get(e.pointerId.toString());
  92884. if (touch) {
  92885. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92886. }
  92887. }
  92888. this._deltaJoystickVector.x = 0;
  92889. this._deltaJoystickVector.y = 0;
  92890. this._touches.remove(e.pointerId.toString());
  92891. };
  92892. /**
  92893. * Change the color of the virtual joystick
  92894. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  92895. */
  92896. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  92897. this._joystickColor = newColor;
  92898. };
  92899. /**
  92900. * Defines a callback to call when the joystick is touched
  92901. * @param action defines the callback
  92902. */
  92903. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  92904. this._action = action;
  92905. };
  92906. /**
  92907. * Defines which axis you'd like to control for left & right
  92908. * @param axis defines the axis to use
  92909. */
  92910. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  92911. switch (axis) {
  92912. case JoystickAxis.X:
  92913. case JoystickAxis.Y:
  92914. case JoystickAxis.Z:
  92915. this._axisTargetedByLeftAndRight = axis;
  92916. break;
  92917. default:
  92918. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  92919. break;
  92920. }
  92921. };
  92922. /**
  92923. * Defines which axis you'd like to control for up & down
  92924. * @param axis defines the axis to use
  92925. */
  92926. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  92927. switch (axis) {
  92928. case JoystickAxis.X:
  92929. case JoystickAxis.Y:
  92930. case JoystickAxis.Z:
  92931. this._axisTargetedByUpAndDown = axis;
  92932. break;
  92933. default:
  92934. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  92935. break;
  92936. }
  92937. };
  92938. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  92939. var _this = this;
  92940. if (this.pressed) {
  92941. this._touches.forEach(function (key, touch) {
  92942. if (touch.pointerId === _this._joystickPointerID) {
  92943. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  92944. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  92945. VirtualJoystick.vjCanvasContext.beginPath();
  92946. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92947. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92948. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  92949. VirtualJoystick.vjCanvasContext.stroke();
  92950. VirtualJoystick.vjCanvasContext.closePath();
  92951. VirtualJoystick.vjCanvasContext.beginPath();
  92952. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92953. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  92954. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  92955. VirtualJoystick.vjCanvasContext.stroke();
  92956. VirtualJoystick.vjCanvasContext.closePath();
  92957. VirtualJoystick.vjCanvasContext.beginPath();
  92958. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  92959. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  92960. VirtualJoystick.vjCanvasContext.stroke();
  92961. VirtualJoystick.vjCanvasContext.closePath();
  92962. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  92963. }
  92964. else {
  92965. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  92966. VirtualJoystick.vjCanvasContext.beginPath();
  92967. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  92968. VirtualJoystick.vjCanvasContext.beginPath();
  92969. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  92970. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  92971. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  92972. VirtualJoystick.vjCanvasContext.stroke();
  92973. VirtualJoystick.vjCanvasContext.closePath();
  92974. touch.prevX = touch.x;
  92975. touch.prevY = touch.y;
  92976. }
  92977. ;
  92978. });
  92979. }
  92980. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  92981. };
  92982. /**
  92983. * Release internal HTML canvas
  92984. */
  92985. VirtualJoystick.prototype.releaseCanvas = function () {
  92986. if (VirtualJoystick.vjCanvas) {
  92987. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  92988. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  92989. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  92990. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  92991. window.removeEventListener("resize", this._onResize);
  92992. document.body.removeChild(VirtualJoystick.vjCanvas);
  92993. VirtualJoystick.vjCanvas = null;
  92994. }
  92995. };
  92996. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  92997. VirtualJoystick._globalJoystickIndex = 0;
  92998. return VirtualJoystick;
  92999. }());
  93000. BABYLON.VirtualJoystick = VirtualJoystick;
  93001. })(BABYLON || (BABYLON = {}));
  93002. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93003. var BABYLON;
  93004. (function (BABYLON) {
  93005. // We're mainly based on the logic defined into the FreeCamera code
  93006. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93007. __extends(VirtualJoysticksCamera, _super);
  93008. function VirtualJoysticksCamera(name, position, scene) {
  93009. var _this = _super.call(this, name, position, scene) || this;
  93010. _this.inputs.addVirtualJoystick();
  93011. return _this;
  93012. }
  93013. VirtualJoysticksCamera.prototype.getClassName = function () {
  93014. return "VirtualJoysticksCamera";
  93015. };
  93016. return VirtualJoysticksCamera;
  93017. }(BABYLON.FreeCamera));
  93018. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93019. })(BABYLON || (BABYLON = {}));
  93020. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93021. var BABYLON;
  93022. (function (BABYLON) {
  93023. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93024. function FreeCameraVirtualJoystickInput() {
  93025. }
  93026. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93027. return this._leftjoystick;
  93028. };
  93029. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93030. return this._rightjoystick;
  93031. };
  93032. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93033. if (this._leftjoystick) {
  93034. var camera = this.camera;
  93035. var speed = camera._computeLocalCameraSpeed() * 50;
  93036. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93037. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93038. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93039. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93040. if (!this._leftjoystick.pressed) {
  93041. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93042. }
  93043. if (!this._rightjoystick.pressed) {
  93044. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93045. }
  93046. }
  93047. };
  93048. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93049. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93050. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93051. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93052. this._leftjoystick.setJoystickSensibility(0.15);
  93053. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93054. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93055. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93056. this._rightjoystick.reverseUpDown = true;
  93057. this._rightjoystick.setJoystickSensibility(0.05);
  93058. this._rightjoystick.setJoystickColor("yellow");
  93059. };
  93060. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93061. this._leftjoystick.releaseCanvas();
  93062. this._rightjoystick.releaseCanvas();
  93063. };
  93064. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93065. return "FreeCameraVirtualJoystickInput";
  93066. };
  93067. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93068. return "virtualJoystick";
  93069. };
  93070. return FreeCameraVirtualJoystickInput;
  93071. }());
  93072. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93073. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93074. })(BABYLON || (BABYLON = {}));
  93075. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93076. var BABYLON;
  93077. (function (BABYLON) {
  93078. var SimplificationSettings = /** @class */ (function () {
  93079. function SimplificationSettings(quality, distance, optimizeMesh) {
  93080. this.quality = quality;
  93081. this.distance = distance;
  93082. this.optimizeMesh = optimizeMesh;
  93083. }
  93084. return SimplificationSettings;
  93085. }());
  93086. BABYLON.SimplificationSettings = SimplificationSettings;
  93087. var SimplificationQueue = /** @class */ (function () {
  93088. function SimplificationQueue() {
  93089. this.running = false;
  93090. this._simplificationArray = [];
  93091. }
  93092. SimplificationQueue.prototype.addTask = function (task) {
  93093. this._simplificationArray.push(task);
  93094. };
  93095. SimplificationQueue.prototype.executeNext = function () {
  93096. var task = this._simplificationArray.pop();
  93097. if (task) {
  93098. this.running = true;
  93099. this.runSimplification(task);
  93100. }
  93101. else {
  93102. this.running = false;
  93103. }
  93104. };
  93105. SimplificationQueue.prototype.runSimplification = function (task) {
  93106. var _this = this;
  93107. if (task.parallelProcessing) {
  93108. //parallel simplifier
  93109. task.settings.forEach(function (setting) {
  93110. var simplifier = _this.getSimplifier(task);
  93111. simplifier.simplify(setting, function (newMesh) {
  93112. task.mesh.addLODLevel(setting.distance, newMesh);
  93113. newMesh.isVisible = true;
  93114. //check if it is the last
  93115. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93116. //all done, run the success callback.
  93117. task.successCallback();
  93118. }
  93119. _this.executeNext();
  93120. });
  93121. });
  93122. }
  93123. else {
  93124. //single simplifier.
  93125. var simplifier = this.getSimplifier(task);
  93126. var runDecimation = function (setting, callback) {
  93127. simplifier.simplify(setting, function (newMesh) {
  93128. task.mesh.addLODLevel(setting.distance, newMesh);
  93129. newMesh.isVisible = true;
  93130. //run the next quality level
  93131. callback();
  93132. });
  93133. };
  93134. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93135. runDecimation(task.settings[loop.index], function () {
  93136. loop.executeNext();
  93137. });
  93138. }, function () {
  93139. //execution ended, run the success callback.
  93140. if (task.successCallback) {
  93141. task.successCallback();
  93142. }
  93143. _this.executeNext();
  93144. });
  93145. }
  93146. };
  93147. SimplificationQueue.prototype.getSimplifier = function (task) {
  93148. switch (task.simplificationType) {
  93149. case SimplificationType.QUADRATIC:
  93150. default:
  93151. return new QuadraticErrorSimplification(task.mesh);
  93152. }
  93153. };
  93154. return SimplificationQueue;
  93155. }());
  93156. BABYLON.SimplificationQueue = SimplificationQueue;
  93157. /**
  93158. * The implemented types of simplification
  93159. * At the moment only Quadratic Error Decimation is implemented
  93160. */
  93161. var SimplificationType;
  93162. (function (SimplificationType) {
  93163. /** Quadratic error decimation */
  93164. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93165. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93166. var DecimationTriangle = /** @class */ (function () {
  93167. function DecimationTriangle(vertices) {
  93168. this.vertices = vertices;
  93169. this.error = new Array(4);
  93170. this.deleted = false;
  93171. this.isDirty = false;
  93172. this.deletePending = false;
  93173. this.borderFactor = 0;
  93174. }
  93175. return DecimationTriangle;
  93176. }());
  93177. BABYLON.DecimationTriangle = DecimationTriangle;
  93178. var DecimationVertex = /** @class */ (function () {
  93179. function DecimationVertex(position, id) {
  93180. this.position = position;
  93181. this.id = id;
  93182. this.isBorder = true;
  93183. this.q = new QuadraticMatrix();
  93184. this.triangleCount = 0;
  93185. this.triangleStart = 0;
  93186. this.originalOffsets = [];
  93187. }
  93188. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93189. this.position.copyFrom(newPosition);
  93190. };
  93191. return DecimationVertex;
  93192. }());
  93193. BABYLON.DecimationVertex = DecimationVertex;
  93194. var QuadraticMatrix = /** @class */ (function () {
  93195. function QuadraticMatrix(data) {
  93196. this.data = new Array(10);
  93197. for (var i = 0; i < 10; ++i) {
  93198. if (data && data[i]) {
  93199. this.data[i] = data[i];
  93200. }
  93201. else {
  93202. this.data[i] = 0;
  93203. }
  93204. }
  93205. }
  93206. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93207. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93208. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93209. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93210. return det;
  93211. };
  93212. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93213. for (var i = 0; i < 10; ++i) {
  93214. this.data[i] += matrix.data[i];
  93215. }
  93216. };
  93217. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93218. for (var i = 0; i < 10; ++i) {
  93219. this.data[i] += data[i];
  93220. }
  93221. };
  93222. QuadraticMatrix.prototype.add = function (matrix) {
  93223. var m = new QuadraticMatrix();
  93224. for (var i = 0; i < 10; ++i) {
  93225. m.data[i] = this.data[i] + matrix.data[i];
  93226. }
  93227. return m;
  93228. };
  93229. QuadraticMatrix.FromData = function (a, b, c, d) {
  93230. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93231. };
  93232. //returning an array to avoid garbage collection
  93233. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93234. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93235. };
  93236. return QuadraticMatrix;
  93237. }());
  93238. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93239. var Reference = /** @class */ (function () {
  93240. function Reference(vertexId, triangleId) {
  93241. this.vertexId = vertexId;
  93242. this.triangleId = triangleId;
  93243. }
  93244. return Reference;
  93245. }());
  93246. BABYLON.Reference = Reference;
  93247. /**
  93248. * An implementation of the Quadratic Error simplification algorithm.
  93249. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93250. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93251. * @author RaananW
  93252. */
  93253. var QuadraticErrorSimplification = /** @class */ (function () {
  93254. function QuadraticErrorSimplification(_mesh) {
  93255. this._mesh = _mesh;
  93256. this.syncIterations = 5000;
  93257. this.aggressiveness = 7;
  93258. this.decimationIterations = 100;
  93259. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93260. }
  93261. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93262. var _this = this;
  93263. this.initDecimatedMesh();
  93264. //iterating through the submeshes array, one after the other.
  93265. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93266. _this.initWithMesh(loop.index, function () {
  93267. _this.runDecimation(settings, loop.index, function () {
  93268. loop.executeNext();
  93269. });
  93270. }, settings.optimizeMesh);
  93271. }, function () {
  93272. setTimeout(function () {
  93273. successCallback(_this._reconstructedMesh);
  93274. }, 0);
  93275. });
  93276. };
  93277. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93278. var _this = this;
  93279. var targetCount = ~~(this.triangles.length * settings.quality);
  93280. var deletedTriangles = 0;
  93281. var triangleCount = this.triangles.length;
  93282. var iterationFunction = function (iteration, callback) {
  93283. setTimeout(function () {
  93284. if (iteration % 5 === 0) {
  93285. _this.updateMesh(iteration === 0);
  93286. }
  93287. for (var i = 0; i < _this.triangles.length; ++i) {
  93288. _this.triangles[i].isDirty = false;
  93289. }
  93290. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93291. var trianglesIterator = function (i) {
  93292. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93293. var t = _this.triangles[tIdx];
  93294. if (!t)
  93295. return;
  93296. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93297. return;
  93298. }
  93299. for (var j = 0; j < 3; ++j) {
  93300. if (t.error[j] < threshold) {
  93301. var deleted0 = [];
  93302. var deleted1 = [];
  93303. var v0 = t.vertices[j];
  93304. var v1 = t.vertices[(j + 1) % 3];
  93305. if (v0.isBorder || v1.isBorder)
  93306. continue;
  93307. var p = BABYLON.Vector3.Zero();
  93308. var n = BABYLON.Vector3.Zero();
  93309. var uv = BABYLON.Vector2.Zero();
  93310. var color = new BABYLON.Color4(0, 0, 0, 1);
  93311. _this.calculateError(v0, v1, p, n, uv, color);
  93312. var delTr = new Array();
  93313. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93314. continue;
  93315. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93316. continue;
  93317. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93318. continue;
  93319. var uniqueArray = new Array();
  93320. delTr.forEach(function (deletedT) {
  93321. if (uniqueArray.indexOf(deletedT) === -1) {
  93322. deletedT.deletePending = true;
  93323. uniqueArray.push(deletedT);
  93324. }
  93325. });
  93326. if (uniqueArray.length % 2 !== 0) {
  93327. continue;
  93328. }
  93329. v0.q = v1.q.add(v0.q);
  93330. v0.updatePosition(p);
  93331. var tStart = _this.references.length;
  93332. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93333. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93334. var tCount = _this.references.length - tStart;
  93335. if (tCount <= v0.triangleCount) {
  93336. if (tCount) {
  93337. for (var c = 0; c < tCount; c++) {
  93338. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93339. }
  93340. }
  93341. }
  93342. else {
  93343. v0.triangleStart = tStart;
  93344. }
  93345. v0.triangleCount = tCount;
  93346. break;
  93347. }
  93348. }
  93349. };
  93350. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93351. }, 0);
  93352. };
  93353. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93354. if (triangleCount - deletedTriangles <= targetCount)
  93355. loop.breakLoop();
  93356. else {
  93357. iterationFunction(loop.index, function () {
  93358. loop.executeNext();
  93359. });
  93360. }
  93361. }, function () {
  93362. setTimeout(function () {
  93363. //reconstruct this part of the mesh
  93364. _this.reconstructMesh(submeshIndex);
  93365. successCallback();
  93366. }, 0);
  93367. });
  93368. };
  93369. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93370. var _this = this;
  93371. this.vertices = [];
  93372. this.triangles = [];
  93373. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93374. var indices = this._mesh.getIndices();
  93375. var submesh = this._mesh.subMeshes[submeshIndex];
  93376. var findInVertices = function (positionToSearch) {
  93377. if (optimizeMesh) {
  93378. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93379. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93380. return _this.vertices[ii];
  93381. }
  93382. }
  93383. }
  93384. return null;
  93385. };
  93386. var vertexReferences = [];
  93387. var vertexInit = function (i) {
  93388. if (!positionData) {
  93389. return;
  93390. }
  93391. var offset = i + submesh.verticesStart;
  93392. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  93393. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  93394. vertex.originalOffsets.push(offset);
  93395. if (vertex.id === _this.vertices.length) {
  93396. _this.vertices.push(vertex);
  93397. }
  93398. vertexReferences.push(vertex.id);
  93399. };
  93400. //var totalVertices = mesh.getTotalVertices();
  93401. var totalVertices = submesh.verticesCount;
  93402. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  93403. var indicesInit = function (i) {
  93404. if (!indices) {
  93405. return;
  93406. }
  93407. var offset = (submesh.indexStart / 3) + i;
  93408. var pos = (offset * 3);
  93409. var i0 = indices[pos + 0];
  93410. var i1 = indices[pos + 1];
  93411. var i2 = indices[pos + 2];
  93412. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  93413. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  93414. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  93415. var triangle = new DecimationTriangle([v0, v1, v2]);
  93416. triangle.originalOffset = pos;
  93417. _this.triangles.push(triangle);
  93418. };
  93419. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  93420. _this.init(callback);
  93421. });
  93422. });
  93423. };
  93424. QuadraticErrorSimplification.prototype.init = function (callback) {
  93425. var _this = this;
  93426. var triangleInit1 = function (i) {
  93427. var t = _this.triangles[i];
  93428. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  93429. for (var j = 0; j < 3; j++) {
  93430. 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))));
  93431. }
  93432. };
  93433. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  93434. var triangleInit2 = function (i) {
  93435. var t = _this.triangles[i];
  93436. for (var j = 0; j < 3; ++j) {
  93437. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  93438. }
  93439. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93440. };
  93441. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  93442. callback();
  93443. });
  93444. });
  93445. };
  93446. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  93447. var newTriangles = [];
  93448. var i;
  93449. for (i = 0; i < this.vertices.length; ++i) {
  93450. this.vertices[i].triangleCount = 0;
  93451. }
  93452. var t;
  93453. var j;
  93454. for (i = 0; i < this.triangles.length; ++i) {
  93455. if (!this.triangles[i].deleted) {
  93456. t = this.triangles[i];
  93457. for (j = 0; j < 3; ++j) {
  93458. t.vertices[j].triangleCount = 1;
  93459. }
  93460. newTriangles.push(t);
  93461. }
  93462. }
  93463. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  93464. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  93465. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  93466. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  93467. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  93468. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93469. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  93470. var vertexCount = 0;
  93471. for (i = 0; i < this.vertices.length; ++i) {
  93472. var vertex = this.vertices[i];
  93473. vertex.id = vertexCount;
  93474. if (vertex.triangleCount) {
  93475. vertex.originalOffsets.forEach(function (originalOffset) {
  93476. if (!normalData) {
  93477. return;
  93478. }
  93479. newPositionData.push(vertex.position.x);
  93480. newPositionData.push(vertex.position.y);
  93481. newPositionData.push(vertex.position.z);
  93482. newNormalData.push(normalData[originalOffset * 3]);
  93483. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  93484. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  93485. if (uvs && uvs.length) {
  93486. newUVsData.push(uvs[(originalOffset * 2)]);
  93487. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  93488. }
  93489. else if (colorsData && colorsData.length) {
  93490. newColorsData.push(colorsData[(originalOffset * 4)]);
  93491. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  93492. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  93493. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  93494. }
  93495. ++vertexCount;
  93496. });
  93497. }
  93498. }
  93499. var startingIndex = this._reconstructedMesh.getTotalIndices();
  93500. var startingVertex = this._reconstructedMesh.getTotalVertices();
  93501. var submeshesArray = this._reconstructedMesh.subMeshes;
  93502. this._reconstructedMesh.subMeshes = [];
  93503. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  93504. var originalIndices = this._mesh.getIndices();
  93505. for (i = 0; i < newTriangles.length; ++i) {
  93506. t = newTriangles[i]; //now get the new referencing point for each vertex
  93507. [0, 1, 2].forEach(function (idx) {
  93508. var id = originalIndices[t.originalOffset + idx];
  93509. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  93510. if (offset < 0)
  93511. offset = 0;
  93512. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  93513. });
  93514. }
  93515. //overwriting the old vertex buffers and indices.
  93516. this._reconstructedMesh.setIndices(newIndicesArray);
  93517. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  93518. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  93519. if (newUVsData.length > 0)
  93520. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  93521. if (newColorsData.length > 0)
  93522. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  93523. //create submesh
  93524. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  93525. if (submeshIndex > 0) {
  93526. this._reconstructedMesh.subMeshes = [];
  93527. submeshesArray.forEach(function (submesh) {
  93528. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  93529. });
  93530. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  93531. }
  93532. };
  93533. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  93534. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  93535. this._reconstructedMesh.material = this._mesh.material;
  93536. this._reconstructedMesh.parent = this._mesh.parent;
  93537. this._reconstructedMesh.isVisible = false;
  93538. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  93539. };
  93540. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  93541. for (var i = 0; i < vertex1.triangleCount; ++i) {
  93542. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  93543. if (t.deleted)
  93544. continue;
  93545. var s = this.references[vertex1.triangleStart + i].vertexId;
  93546. var v1 = t.vertices[(s + 1) % 3];
  93547. var v2 = t.vertices[(s + 2) % 3];
  93548. if ((v1 === vertex2 || v2 === vertex2)) {
  93549. deletedArray[i] = true;
  93550. delTr.push(t);
  93551. continue;
  93552. }
  93553. var d1 = v1.position.subtract(point);
  93554. d1 = d1.normalize();
  93555. var d2 = v2.position.subtract(point);
  93556. d2 = d2.normalize();
  93557. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  93558. return true;
  93559. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  93560. deletedArray[i] = false;
  93561. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  93562. return true;
  93563. }
  93564. return false;
  93565. };
  93566. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  93567. var newDeleted = deletedTriangles;
  93568. for (var i = 0; i < vertex.triangleCount; ++i) {
  93569. var ref = this.references[vertex.triangleStart + i];
  93570. var t = this.triangles[ref.triangleId];
  93571. if (t.deleted)
  93572. continue;
  93573. if (deletedArray[i] && t.deletePending) {
  93574. t.deleted = true;
  93575. newDeleted++;
  93576. continue;
  93577. }
  93578. t.vertices[ref.vertexId] = origVertex;
  93579. t.isDirty = true;
  93580. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  93581. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  93582. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  93583. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  93584. this.references.push(ref);
  93585. }
  93586. return newDeleted;
  93587. };
  93588. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  93589. for (var i = 0; i < this.vertices.length; ++i) {
  93590. var vCount = [];
  93591. var vId = [];
  93592. var v = this.vertices[i];
  93593. var j;
  93594. for (j = 0; j < v.triangleCount; ++j) {
  93595. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  93596. for (var ii = 0; ii < 3; ii++) {
  93597. var ofs = 0;
  93598. var vv = triangle.vertices[ii];
  93599. while (ofs < vCount.length) {
  93600. if (vId[ofs] === vv.id)
  93601. break;
  93602. ++ofs;
  93603. }
  93604. if (ofs === vCount.length) {
  93605. vCount.push(1);
  93606. vId.push(vv.id);
  93607. }
  93608. else {
  93609. vCount[ofs]++;
  93610. }
  93611. }
  93612. }
  93613. for (j = 0; j < vCount.length; ++j) {
  93614. if (vCount[j] === 1) {
  93615. this.vertices[vId[j]].isBorder = true;
  93616. }
  93617. else {
  93618. this.vertices[vId[j]].isBorder = false;
  93619. }
  93620. }
  93621. }
  93622. };
  93623. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  93624. if (identifyBorders === void 0) { identifyBorders = false; }
  93625. var i;
  93626. if (!identifyBorders) {
  93627. var newTrianglesVector = [];
  93628. for (i = 0; i < this.triangles.length; ++i) {
  93629. if (!this.triangles[i].deleted) {
  93630. newTrianglesVector.push(this.triangles[i]);
  93631. }
  93632. }
  93633. this.triangles = newTrianglesVector;
  93634. }
  93635. for (i = 0; i < this.vertices.length; ++i) {
  93636. this.vertices[i].triangleCount = 0;
  93637. this.vertices[i].triangleStart = 0;
  93638. }
  93639. var t;
  93640. var j;
  93641. var v;
  93642. for (i = 0; i < this.triangles.length; ++i) {
  93643. t = this.triangles[i];
  93644. for (j = 0; j < 3; ++j) {
  93645. v = t.vertices[j];
  93646. v.triangleCount++;
  93647. }
  93648. }
  93649. var tStart = 0;
  93650. for (i = 0; i < this.vertices.length; ++i) {
  93651. this.vertices[i].triangleStart = tStart;
  93652. tStart += this.vertices[i].triangleCount;
  93653. this.vertices[i].triangleCount = 0;
  93654. }
  93655. var newReferences = new Array(this.triangles.length * 3);
  93656. for (i = 0; i < this.triangles.length; ++i) {
  93657. t = this.triangles[i];
  93658. for (j = 0; j < 3; ++j) {
  93659. v = t.vertices[j];
  93660. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  93661. v.triangleCount++;
  93662. }
  93663. }
  93664. this.references = newReferences;
  93665. if (identifyBorders) {
  93666. this.identifyBorder();
  93667. }
  93668. };
  93669. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  93670. var x = point.x;
  93671. var y = point.y;
  93672. var z = point.z;
  93673. 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
  93674. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  93675. };
  93676. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  93677. var q = vertex1.q.add(vertex2.q);
  93678. var border = vertex1.isBorder && vertex2.isBorder;
  93679. var error = 0;
  93680. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  93681. if (qDet !== 0 && !border) {
  93682. if (!pointResult) {
  93683. pointResult = BABYLON.Vector3.Zero();
  93684. }
  93685. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  93686. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  93687. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  93688. error = this.vertexError(q, pointResult);
  93689. }
  93690. else {
  93691. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  93692. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  93693. var error1 = this.vertexError(q, vertex1.position);
  93694. var error2 = this.vertexError(q, vertex2.position);
  93695. var error3 = this.vertexError(q, p3);
  93696. error = Math.min(error1, error2, error3);
  93697. if (error === error1) {
  93698. if (pointResult) {
  93699. pointResult.copyFrom(vertex1.position);
  93700. }
  93701. }
  93702. else if (error === error2) {
  93703. if (pointResult) {
  93704. pointResult.copyFrom(vertex2.position);
  93705. }
  93706. }
  93707. else {
  93708. if (pointResult) {
  93709. pointResult.copyFrom(p3);
  93710. }
  93711. }
  93712. }
  93713. return error;
  93714. };
  93715. return QuadraticErrorSimplification;
  93716. }());
  93717. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  93718. })(BABYLON || (BABYLON = {}));
  93719. //# sourceMappingURL=babylon.meshSimplification.js.map
  93720. var BABYLON;
  93721. (function (BABYLON) {
  93722. var MeshLODLevel = /** @class */ (function () {
  93723. function MeshLODLevel(distance, mesh) {
  93724. this.distance = distance;
  93725. this.mesh = mesh;
  93726. }
  93727. return MeshLODLevel;
  93728. }());
  93729. BABYLON.MeshLODLevel = MeshLODLevel;
  93730. })(BABYLON || (BABYLON = {}));
  93731. //# sourceMappingURL=babylon.meshLODLevel.js.map
  93732. var BABYLON;
  93733. (function (BABYLON) {
  93734. /**
  93735. * Defines the root class used to create scene optimization to use with SceneOptimizer
  93736. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93737. */
  93738. var SceneOptimization = /** @class */ (function () {
  93739. /**
  93740. * Creates the SceneOptimization object
  93741. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93742. * @param desc defines the description associated with the optimization
  93743. */
  93744. function SceneOptimization(
  93745. /**
  93746. * Defines the priority of this optimization (0 by default which means first in the list)
  93747. */
  93748. priority) {
  93749. if (priority === void 0) { priority = 0; }
  93750. this.priority = priority;
  93751. }
  93752. /**
  93753. * Gets a string describing the action executed by the current optimization
  93754. * @returns description string
  93755. */
  93756. SceneOptimization.prototype.getDescription = function () {
  93757. return "";
  93758. };
  93759. /**
  93760. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93761. * @param scene defines the current scene where to apply this optimization
  93762. * @param optimizer defines the current optimizer
  93763. * @returns true if everything that can be done was applied
  93764. */
  93765. SceneOptimization.prototype.apply = function (scene, optimizer) {
  93766. return true;
  93767. };
  93768. ;
  93769. return SceneOptimization;
  93770. }());
  93771. BABYLON.SceneOptimization = SceneOptimization;
  93772. /**
  93773. * Defines an optimization used to reduce the size of render target textures
  93774. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93775. */
  93776. var TextureOptimization = /** @class */ (function (_super) {
  93777. __extends(TextureOptimization, _super);
  93778. /**
  93779. * Creates the TextureOptimization object
  93780. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93781. * @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
  93782. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93783. */
  93784. function TextureOptimization(
  93785. /**
  93786. * Defines the priority of this optimization (0 by default which means first in the list)
  93787. */
  93788. priority,
  93789. /**
  93790. * 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
  93791. */
  93792. maximumSize,
  93793. /**
  93794. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  93795. */
  93796. step) {
  93797. if (priority === void 0) { priority = 0; }
  93798. if (maximumSize === void 0) { maximumSize = 1024; }
  93799. if (step === void 0) { step = 0.5; }
  93800. var _this = _super.call(this, priority) || this;
  93801. _this.priority = priority;
  93802. _this.maximumSize = maximumSize;
  93803. _this.step = step;
  93804. return _this;
  93805. }
  93806. /**
  93807. * Gets a string describing the action executed by the current optimization
  93808. * @returns description string
  93809. */
  93810. TextureOptimization.prototype.getDescription = function () {
  93811. return "Reducing render target texture size to " + this.maximumSize;
  93812. };
  93813. /**
  93814. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93815. * @param scene defines the current scene where to apply this optimization
  93816. * @param optimizer defines the current optimizer
  93817. * @returns true if everything that can be done was applied
  93818. */
  93819. TextureOptimization.prototype.apply = function (scene, optimizer) {
  93820. var allDone = true;
  93821. for (var index = 0; index < scene.textures.length; index++) {
  93822. var texture = scene.textures[index];
  93823. if (!texture.canRescale || texture.getContext) {
  93824. continue;
  93825. }
  93826. var currentSize = texture.getSize();
  93827. var maxDimension = Math.max(currentSize.width, currentSize.height);
  93828. if (maxDimension > this.maximumSize) {
  93829. texture.scale(this.step);
  93830. allDone = false;
  93831. }
  93832. }
  93833. return allDone;
  93834. };
  93835. return TextureOptimization;
  93836. }(SceneOptimization));
  93837. BABYLON.TextureOptimization = TextureOptimization;
  93838. /**
  93839. * Defines an optimization used to increase or decrease the rendering resolution
  93840. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93841. */
  93842. var HardwareScalingOptimization = /** @class */ (function (_super) {
  93843. __extends(HardwareScalingOptimization, _super);
  93844. /**
  93845. * Creates the HardwareScalingOptimization object
  93846. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  93847. * @param maximumScale defines the maximum scale to use (2 by default)
  93848. * @param step defines the step to use between two passes (0.5 by default)
  93849. */
  93850. function HardwareScalingOptimization(
  93851. /**
  93852. * Defines the priority of this optimization (0 by default which means first in the list)
  93853. */
  93854. priority,
  93855. /**
  93856. * Defines the maximum scale to use (2 by default)
  93857. */
  93858. maximumScale,
  93859. /**
  93860. * Defines the step to use between two passes (0.5 by default)
  93861. */
  93862. step) {
  93863. if (priority === void 0) { priority = 0; }
  93864. if (maximumScale === void 0) { maximumScale = 2; }
  93865. if (step === void 0) { step = 0.25; }
  93866. var _this = _super.call(this, priority) || this;
  93867. _this.priority = priority;
  93868. _this.maximumScale = maximumScale;
  93869. _this.step = step;
  93870. _this._currentScale = -1;
  93871. _this._directionOffset = 1;
  93872. return _this;
  93873. }
  93874. /**
  93875. * Gets a string describing the action executed by the current optimization
  93876. * @return description string
  93877. */
  93878. HardwareScalingOptimization.prototype.getDescription = function () {
  93879. return "Setting hardware scaling level to " + this._currentScale;
  93880. };
  93881. /**
  93882. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93883. * @param scene defines the current scene where to apply this optimization
  93884. * @param optimizer defines the current optimizer
  93885. * @returns true if everything that can be done was applied
  93886. */
  93887. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  93888. if (this._currentScale === -1) {
  93889. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  93890. if (this._currentScale > this.maximumScale) {
  93891. this._directionOffset = -1;
  93892. }
  93893. }
  93894. this._currentScale += this._directionOffset * this.step;
  93895. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  93896. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  93897. };
  93898. ;
  93899. return HardwareScalingOptimization;
  93900. }(SceneOptimization));
  93901. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  93902. /**
  93903. * Defines an optimization used to remove shadows
  93904. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93905. */
  93906. var ShadowsOptimization = /** @class */ (function (_super) {
  93907. __extends(ShadowsOptimization, _super);
  93908. function ShadowsOptimization() {
  93909. return _super !== null && _super.apply(this, arguments) || this;
  93910. }
  93911. /**
  93912. * Gets a string describing the action executed by the current optimization
  93913. * @return description string
  93914. */
  93915. ShadowsOptimization.prototype.getDescription = function () {
  93916. return "Turning shadows on/off";
  93917. };
  93918. /**
  93919. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93920. * @param scene defines the current scene where to apply this optimization
  93921. * @param optimizer defines the current optimizer
  93922. * @returns true if everything that can be done was applied
  93923. */
  93924. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  93925. scene.shadowsEnabled = optimizer.isInImprovementMode;
  93926. return true;
  93927. };
  93928. ;
  93929. return ShadowsOptimization;
  93930. }(SceneOptimization));
  93931. BABYLON.ShadowsOptimization = ShadowsOptimization;
  93932. /**
  93933. * Defines an optimization used to turn post-processes off
  93934. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93935. */
  93936. var PostProcessesOptimization = /** @class */ (function (_super) {
  93937. __extends(PostProcessesOptimization, _super);
  93938. function PostProcessesOptimization() {
  93939. return _super !== null && _super.apply(this, arguments) || this;
  93940. }
  93941. /**
  93942. * Gets a string describing the action executed by the current optimization
  93943. * @return description string
  93944. */
  93945. PostProcessesOptimization.prototype.getDescription = function () {
  93946. return "Turning post-processes on/off";
  93947. };
  93948. /**
  93949. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93950. * @param scene defines the current scene where to apply this optimization
  93951. * @param optimizer defines the current optimizer
  93952. * @returns true if everything that can be done was applied
  93953. */
  93954. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  93955. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  93956. return true;
  93957. };
  93958. ;
  93959. return PostProcessesOptimization;
  93960. }(SceneOptimization));
  93961. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  93962. /**
  93963. * Defines an optimization used to turn lens flares off
  93964. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93965. */
  93966. var LensFlaresOptimization = /** @class */ (function (_super) {
  93967. __extends(LensFlaresOptimization, _super);
  93968. function LensFlaresOptimization() {
  93969. return _super !== null && _super.apply(this, arguments) || this;
  93970. }
  93971. /**
  93972. * Gets a string describing the action executed by the current optimization
  93973. * @return description string
  93974. */
  93975. LensFlaresOptimization.prototype.getDescription = function () {
  93976. return "Turning lens flares on/off";
  93977. };
  93978. /**
  93979. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  93980. * @param scene defines the current scene where to apply this optimization
  93981. * @param optimizer defines the current optimizer
  93982. * @returns true if everything that can be done was applied
  93983. */
  93984. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  93985. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  93986. return true;
  93987. };
  93988. ;
  93989. return LensFlaresOptimization;
  93990. }(SceneOptimization));
  93991. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  93992. /**
  93993. * Defines an optimization based on user defined callback.
  93994. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  93995. */
  93996. var CustomOptimization = /** @class */ (function (_super) {
  93997. __extends(CustomOptimization, _super);
  93998. function CustomOptimization() {
  93999. return _super !== null && _super.apply(this, arguments) || this;
  94000. }
  94001. /**
  94002. * Gets a string describing the action executed by the current optimization
  94003. * @returns description string
  94004. */
  94005. CustomOptimization.prototype.getDescription = function () {
  94006. if (this.onGetDescription) {
  94007. return this.onGetDescription();
  94008. }
  94009. return "Running user defined callback";
  94010. };
  94011. /**
  94012. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94013. * @param scene defines the current scene where to apply this optimization
  94014. * @param optimizer defines the current optimizer
  94015. * @returns true if everything that can be done was applied
  94016. */
  94017. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94018. if (this.onApply) {
  94019. return this.onApply(scene, optimizer);
  94020. }
  94021. return true;
  94022. };
  94023. ;
  94024. return CustomOptimization;
  94025. }(SceneOptimization));
  94026. BABYLON.CustomOptimization = CustomOptimization;
  94027. /**
  94028. * Defines an optimization used to turn particles off
  94029. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94030. */
  94031. var ParticlesOptimization = /** @class */ (function (_super) {
  94032. __extends(ParticlesOptimization, _super);
  94033. function ParticlesOptimization() {
  94034. return _super !== null && _super.apply(this, arguments) || this;
  94035. }
  94036. /**
  94037. * Gets a string describing the action executed by the current optimization
  94038. * @return description string
  94039. */
  94040. ParticlesOptimization.prototype.getDescription = function () {
  94041. return "Turning particles on/off";
  94042. };
  94043. /**
  94044. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94045. * @param scene defines the current scene where to apply this optimization
  94046. * @param optimizer defines the current optimizer
  94047. * @returns true if everything that can be done was applied
  94048. */
  94049. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94050. scene.particlesEnabled = optimizer.isInImprovementMode;
  94051. return true;
  94052. };
  94053. ;
  94054. return ParticlesOptimization;
  94055. }(SceneOptimization));
  94056. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94057. /**
  94058. * Defines an optimization used to turn render targets off
  94059. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94060. */
  94061. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94062. __extends(RenderTargetsOptimization, _super);
  94063. function RenderTargetsOptimization() {
  94064. return _super !== null && _super.apply(this, arguments) || this;
  94065. }
  94066. /**
  94067. * Gets a string describing the action executed by the current optimization
  94068. * @return description string
  94069. */
  94070. RenderTargetsOptimization.prototype.getDescription = function () {
  94071. return "Turning render targets off";
  94072. };
  94073. /**
  94074. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94075. * @param scene defines the current scene where to apply this optimization
  94076. * @param optimizer defines the current optimizer
  94077. * @returns true if everything that can be done was applied
  94078. */
  94079. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94080. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94081. return true;
  94082. };
  94083. ;
  94084. return RenderTargetsOptimization;
  94085. }(SceneOptimization));
  94086. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94087. /**
  94088. * Defines an optimization used to merge meshes with compatible materials
  94089. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94090. */
  94091. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94092. __extends(MergeMeshesOptimization, _super);
  94093. function MergeMeshesOptimization() {
  94094. var _this = _super !== null && _super.apply(this, arguments) || this;
  94095. _this._canBeMerged = function (abstractMesh) {
  94096. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94097. return false;
  94098. }
  94099. var mesh = abstractMesh;
  94100. if (!mesh.isVisible || !mesh.isEnabled()) {
  94101. return false;
  94102. }
  94103. if (mesh.instances.length > 0) {
  94104. return false;
  94105. }
  94106. if (mesh.skeleton || mesh.hasLODLevels) {
  94107. return false;
  94108. }
  94109. if (mesh.parent) {
  94110. return false;
  94111. }
  94112. return true;
  94113. };
  94114. return _this;
  94115. }
  94116. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94117. /**
  94118. * Gets or sets a boolean which defines if optimization octree has to be updated
  94119. */
  94120. get: function () {
  94121. return MergeMeshesOptimization._UpdateSelectionTree;
  94122. },
  94123. /**
  94124. * Gets or sets a boolean which defines if optimization octree has to be updated
  94125. */
  94126. set: function (value) {
  94127. MergeMeshesOptimization._UpdateSelectionTree = value;
  94128. },
  94129. enumerable: true,
  94130. configurable: true
  94131. });
  94132. /**
  94133. * Gets a string describing the action executed by the current optimization
  94134. * @return description string
  94135. */
  94136. MergeMeshesOptimization.prototype.getDescription = function () {
  94137. return "Merging similar meshes together";
  94138. };
  94139. /**
  94140. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94141. * @param scene defines the current scene where to apply this optimization
  94142. * @param optimizer defines the current optimizer
  94143. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94144. * @returns true if everything that can be done was applied
  94145. */
  94146. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94147. var globalPool = scene.meshes.slice(0);
  94148. var globalLength = globalPool.length;
  94149. for (var index = 0; index < globalLength; index++) {
  94150. var currentPool = new Array();
  94151. var current = globalPool[index];
  94152. // Checks
  94153. if (!this._canBeMerged(current)) {
  94154. continue;
  94155. }
  94156. currentPool.push(current);
  94157. // Find compatible meshes
  94158. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94159. var otherMesh = globalPool[subIndex];
  94160. if (!this._canBeMerged(otherMesh)) {
  94161. continue;
  94162. }
  94163. if (otherMesh.material !== current.material) {
  94164. continue;
  94165. }
  94166. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94167. continue;
  94168. }
  94169. currentPool.push(otherMesh);
  94170. globalLength--;
  94171. globalPool.splice(subIndex, 1);
  94172. subIndex--;
  94173. }
  94174. if (currentPool.length < 2) {
  94175. continue;
  94176. }
  94177. // Merge meshes
  94178. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94179. }
  94180. if (updateSelectionTree != undefined) {
  94181. if (updateSelectionTree) {
  94182. scene.createOrUpdateSelectionOctree();
  94183. }
  94184. }
  94185. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94186. scene.createOrUpdateSelectionOctree();
  94187. }
  94188. return true;
  94189. };
  94190. ;
  94191. MergeMeshesOptimization._UpdateSelectionTree = false;
  94192. return MergeMeshesOptimization;
  94193. }(SceneOptimization));
  94194. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94195. /**
  94196. * Defines a list of options used by SceneOptimizer
  94197. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94198. */
  94199. var SceneOptimizerOptions = /** @class */ (function () {
  94200. /**
  94201. * Creates a new list of options used by SceneOptimizer
  94202. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94203. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94204. */
  94205. function SceneOptimizerOptions(
  94206. /**
  94207. * Defines the target frame rate to reach (60 by default)
  94208. */
  94209. targetFrameRate,
  94210. /**
  94211. * Defines the interval between two checkes (2000ms by default)
  94212. */
  94213. trackerDuration) {
  94214. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94215. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94216. this.targetFrameRate = targetFrameRate;
  94217. this.trackerDuration = trackerDuration;
  94218. /**
  94219. * Gets the list of optimizations to apply
  94220. */
  94221. this.optimizations = new Array();
  94222. }
  94223. /**
  94224. * Add a new optimization
  94225. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94226. * @returns the current SceneOptimizerOptions
  94227. */
  94228. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94229. this.optimizations.push(optimization);
  94230. return this;
  94231. };
  94232. /**
  94233. * Add a new custom optimization
  94234. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94235. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94236. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94237. * @returns the current SceneOptimizerOptions
  94238. */
  94239. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94240. if (priority === void 0) { priority = 0; }
  94241. var optimization = new CustomOptimization(priority);
  94242. optimization.onApply = onApply;
  94243. optimization.onGetDescription = onGetDescription;
  94244. this.optimizations.push(optimization);
  94245. return this;
  94246. };
  94247. /**
  94248. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94249. * @param targetFrameRate defines the target frame rate (60 by default)
  94250. * @returns a SceneOptimizerOptions object
  94251. */
  94252. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94253. var result = new SceneOptimizerOptions(targetFrameRate);
  94254. var priority = 0;
  94255. result.addOptimization(new MergeMeshesOptimization(priority));
  94256. result.addOptimization(new ShadowsOptimization(priority));
  94257. result.addOptimization(new LensFlaresOptimization(priority));
  94258. // Next priority
  94259. priority++;
  94260. result.addOptimization(new PostProcessesOptimization(priority));
  94261. result.addOptimization(new ParticlesOptimization(priority));
  94262. // Next priority
  94263. priority++;
  94264. result.addOptimization(new TextureOptimization(priority, 1024));
  94265. return result;
  94266. };
  94267. /**
  94268. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94269. * @param targetFrameRate defines the target frame rate (60 by default)
  94270. * @returns a SceneOptimizerOptions object
  94271. */
  94272. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94273. var result = new SceneOptimizerOptions(targetFrameRate);
  94274. var priority = 0;
  94275. result.addOptimization(new MergeMeshesOptimization(priority));
  94276. result.addOptimization(new ShadowsOptimization(priority));
  94277. result.addOptimization(new LensFlaresOptimization(priority));
  94278. // Next priority
  94279. priority++;
  94280. result.addOptimization(new PostProcessesOptimization(priority));
  94281. result.addOptimization(new ParticlesOptimization(priority));
  94282. // Next priority
  94283. priority++;
  94284. result.addOptimization(new TextureOptimization(priority, 512));
  94285. // Next priority
  94286. priority++;
  94287. result.addOptimization(new RenderTargetsOptimization(priority));
  94288. // Next priority
  94289. priority++;
  94290. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94291. return result;
  94292. };
  94293. /**
  94294. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94295. * @param targetFrameRate defines the target frame rate (60 by default)
  94296. * @returns a SceneOptimizerOptions object
  94297. */
  94298. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94299. var result = new SceneOptimizerOptions(targetFrameRate);
  94300. var priority = 0;
  94301. result.addOptimization(new MergeMeshesOptimization(priority));
  94302. result.addOptimization(new ShadowsOptimization(priority));
  94303. result.addOptimization(new LensFlaresOptimization(priority));
  94304. // Next priority
  94305. priority++;
  94306. result.addOptimization(new PostProcessesOptimization(priority));
  94307. result.addOptimization(new ParticlesOptimization(priority));
  94308. // Next priority
  94309. priority++;
  94310. result.addOptimization(new TextureOptimization(priority, 256));
  94311. // Next priority
  94312. priority++;
  94313. result.addOptimization(new RenderTargetsOptimization(priority));
  94314. // Next priority
  94315. priority++;
  94316. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94317. return result;
  94318. };
  94319. return SceneOptimizerOptions;
  94320. }());
  94321. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94322. /**
  94323. * Class used to run optimizations in order to reach a target frame rate
  94324. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94325. */
  94326. var SceneOptimizer = /** @class */ (function () {
  94327. /**
  94328. * Creates a new SceneOptimizer
  94329. * @param scene defines the scene to work on
  94330. * @param options defines the options to use with the SceneOptimizer
  94331. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94332. * @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)
  94333. */
  94334. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94335. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94336. if (improvementMode === void 0) { improvementMode = false; }
  94337. var _this = this;
  94338. this._isRunning = false;
  94339. this._currentPriorityLevel = 0;
  94340. this._targetFrameRate = 60;
  94341. this._trackerDuration = 2000;
  94342. this._currentFrameRate = 0;
  94343. this._improvementMode = false;
  94344. /**
  94345. * Defines an observable called when the optimizer reaches the target frame rate
  94346. */
  94347. this.onSuccessObservable = new BABYLON.Observable();
  94348. /**
  94349. * Defines an observable called when the optimizer enables an optimization
  94350. */
  94351. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94352. /**
  94353. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94354. */
  94355. this.onFailureObservable = new BABYLON.Observable();
  94356. if (!options) {
  94357. this._options = new SceneOptimizerOptions();
  94358. }
  94359. else {
  94360. this._options = options;
  94361. }
  94362. if (this._options.targetFrameRate) {
  94363. this._targetFrameRate = this._options.targetFrameRate;
  94364. }
  94365. if (this._options.trackerDuration) {
  94366. this._trackerDuration = this._options.trackerDuration;
  94367. }
  94368. if (autoGeneratePriorities) {
  94369. var priority = 0;
  94370. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94371. var optim = _a[_i];
  94372. optim.priority = priority++;
  94373. }
  94374. }
  94375. this._improvementMode = improvementMode;
  94376. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94377. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94378. _this._sceneDisposeObserver = null;
  94379. _this.dispose();
  94380. });
  94381. }
  94382. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94383. /**
  94384. * Gets a boolean indicating if the optimizer is in improvement mode
  94385. */
  94386. get: function () {
  94387. return this._improvementMode;
  94388. },
  94389. enumerable: true,
  94390. configurable: true
  94391. });
  94392. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  94393. /**
  94394. * Gets the current priority level (0 at start)
  94395. */
  94396. get: function () {
  94397. return this._currentPriorityLevel;
  94398. },
  94399. enumerable: true,
  94400. configurable: true
  94401. });
  94402. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  94403. /**
  94404. * Gets the current frame rate checked by the SceneOptimizer
  94405. */
  94406. get: function () {
  94407. return this._currentFrameRate;
  94408. },
  94409. enumerable: true,
  94410. configurable: true
  94411. });
  94412. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  94413. /**
  94414. * Gets or sets the current target frame rate (60 by default)
  94415. */
  94416. get: function () {
  94417. return this._targetFrameRate;
  94418. },
  94419. /**
  94420. * Gets or sets the current target frame rate (60 by default)
  94421. */
  94422. set: function (value) {
  94423. this._targetFrameRate = value;
  94424. },
  94425. enumerable: true,
  94426. configurable: true
  94427. });
  94428. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  94429. /**
  94430. * Gets or sets the current interval between two checks (every 2000ms by default)
  94431. */
  94432. get: function () {
  94433. return this._trackerDuration;
  94434. },
  94435. /**
  94436. * Gets or sets the current interval between two checks (every 2000ms by default)
  94437. */
  94438. set: function (value) {
  94439. this._trackerDuration = value;
  94440. },
  94441. enumerable: true,
  94442. configurable: true
  94443. });
  94444. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  94445. /**
  94446. * Gets the list of active optimizations
  94447. */
  94448. get: function () {
  94449. return this._options.optimizations;
  94450. },
  94451. enumerable: true,
  94452. configurable: true
  94453. });
  94454. /**
  94455. * Stops the current optimizer
  94456. */
  94457. SceneOptimizer.prototype.stop = function () {
  94458. this._isRunning = false;
  94459. };
  94460. /**
  94461. * Reset the optimizer to initial step (current priority level = 0)
  94462. */
  94463. SceneOptimizer.prototype.reset = function () {
  94464. this._currentPriorityLevel = 0;
  94465. };
  94466. /**
  94467. * Start the optimizer. By default it will try to reach a specific framerate
  94468. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  94469. */
  94470. SceneOptimizer.prototype.start = function () {
  94471. var _this = this;
  94472. if (this._isRunning) {
  94473. return;
  94474. }
  94475. this._isRunning = true;
  94476. // Let's wait for the scene to be ready before running our check
  94477. this._scene.executeWhenReady(function () {
  94478. setTimeout(function () {
  94479. _this._checkCurrentState();
  94480. }, _this._trackerDuration);
  94481. });
  94482. };
  94483. SceneOptimizer.prototype._checkCurrentState = function () {
  94484. var _this = this;
  94485. if (!this._isRunning) {
  94486. return;
  94487. }
  94488. var scene = this._scene;
  94489. var options = this._options;
  94490. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  94491. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  94492. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  94493. this._isRunning = false;
  94494. this.onSuccessObservable.notifyObservers(this);
  94495. return;
  94496. }
  94497. // Apply current level of optimizations
  94498. var allDone = true;
  94499. var noOptimizationApplied = true;
  94500. for (var index = 0; index < options.optimizations.length; index++) {
  94501. var optimization = options.optimizations[index];
  94502. if (optimization.priority === this._currentPriorityLevel) {
  94503. noOptimizationApplied = false;
  94504. allDone = allDone && optimization.apply(scene, this);
  94505. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  94506. }
  94507. }
  94508. // If no optimization was applied, this is a failure :(
  94509. if (noOptimizationApplied) {
  94510. this._isRunning = false;
  94511. this.onFailureObservable.notifyObservers(this);
  94512. return;
  94513. }
  94514. // If all optimizations were done, move to next level
  94515. if (allDone) {
  94516. this._currentPriorityLevel++;
  94517. }
  94518. // Let's the system running for a specific amount of time before checking FPS
  94519. scene.executeWhenReady(function () {
  94520. setTimeout(function () {
  94521. _this._checkCurrentState();
  94522. }, _this._trackerDuration);
  94523. });
  94524. };
  94525. /**
  94526. * Release all resources
  94527. */
  94528. SceneOptimizer.prototype.dispose = function () {
  94529. this.stop();
  94530. this.onSuccessObservable.clear();
  94531. this.onFailureObservable.clear();
  94532. this.onNewOptimizationAppliedObservable.clear();
  94533. if (this._sceneDisposeObserver) {
  94534. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  94535. }
  94536. };
  94537. /**
  94538. * Helper function to create a SceneOptimizer with one single line of code
  94539. * @param scene defines the scene to work on
  94540. * @param options defines the options to use with the SceneOptimizer
  94541. * @param onSuccess defines a callback to call on success
  94542. * @param onFailure defines a callback to call on failure
  94543. * @returns the new SceneOptimizer object
  94544. */
  94545. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  94546. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  94547. if (onSuccess) {
  94548. optimizer.onSuccessObservable.add(function () {
  94549. onSuccess();
  94550. });
  94551. }
  94552. if (onFailure) {
  94553. optimizer.onFailureObservable.add(function () {
  94554. onFailure();
  94555. });
  94556. }
  94557. optimizer.start();
  94558. return optimizer;
  94559. };
  94560. return SceneOptimizer;
  94561. }());
  94562. BABYLON.SceneOptimizer = SceneOptimizer;
  94563. })(BABYLON || (BABYLON = {}));
  94564. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  94565. var BABYLON;
  94566. (function (BABYLON) {
  94567. var OutlineRenderer = /** @class */ (function () {
  94568. function OutlineRenderer(scene) {
  94569. this.zOffset = 1;
  94570. this._scene = scene;
  94571. }
  94572. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  94573. var _this = this;
  94574. if (useOverlay === void 0) { useOverlay = false; }
  94575. var scene = this._scene;
  94576. var engine = this._scene.getEngine();
  94577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  94578. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  94579. return;
  94580. }
  94581. var mesh = subMesh.getRenderingMesh();
  94582. var material = subMesh.getMaterial();
  94583. if (!material || !scene.activeCamera) {
  94584. return;
  94585. }
  94586. engine.enableEffect(this._effect);
  94587. // Logarithmic depth
  94588. if (material.useLogarithmicDepth) {
  94589. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  94590. }
  94591. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  94592. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  94593. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  94594. // Bones
  94595. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  94596. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  94597. }
  94598. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  94599. // Alpha test
  94600. if (material && material.needAlphaTesting()) {
  94601. var alphaTexture = material.getAlphaTestTexture();
  94602. if (alphaTexture) {
  94603. this._effect.setTexture("diffuseSampler", alphaTexture);
  94604. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  94605. }
  94606. }
  94607. engine.setZOffset(-this.zOffset);
  94608. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  94609. engine.setZOffset(0);
  94610. };
  94611. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  94612. var defines = [];
  94613. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  94614. var mesh = subMesh.getMesh();
  94615. var material = subMesh.getMaterial();
  94616. if (material) {
  94617. // Alpha test
  94618. if (material.needAlphaTesting()) {
  94619. defines.push("#define ALPHATEST");
  94620. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  94621. attribs.push(BABYLON.VertexBuffer.UVKind);
  94622. defines.push("#define UV1");
  94623. }
  94624. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  94625. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  94626. defines.push("#define UV2");
  94627. }
  94628. }
  94629. //Logarithmic depth
  94630. if (material.useLogarithmicDepth) {
  94631. defines.push("#define LOGARITHMICDEPTH");
  94632. }
  94633. }
  94634. // Bones
  94635. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  94636. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  94637. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  94638. if (mesh.numBoneInfluencers > 4) {
  94639. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  94640. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  94641. }
  94642. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  94643. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  94644. }
  94645. else {
  94646. defines.push("#define NUM_BONE_INFLUENCERS 0");
  94647. }
  94648. // Instances
  94649. if (useInstances) {
  94650. defines.push("#define INSTANCES");
  94651. attribs.push("world0");
  94652. attribs.push("world1");
  94653. attribs.push("world2");
  94654. attribs.push("world3");
  94655. }
  94656. // Get correct effect
  94657. var join = defines.join("\n");
  94658. if (this._cachedDefines !== join) {
  94659. this._cachedDefines = join;
  94660. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  94661. }
  94662. return this._effect.isReady();
  94663. };
  94664. return OutlineRenderer;
  94665. }());
  94666. BABYLON.OutlineRenderer = OutlineRenderer;
  94667. })(BABYLON || (BABYLON = {}));
  94668. //# sourceMappingURL=babylon.outlineRenderer.js.map
  94669. var BABYLON;
  94670. (function (BABYLON) {
  94671. var FaceAdjacencies = /** @class */ (function () {
  94672. function FaceAdjacencies() {
  94673. this.edges = new Array();
  94674. this.edgesConnectedCount = 0;
  94675. }
  94676. return FaceAdjacencies;
  94677. }());
  94678. var EdgesRenderer = /** @class */ (function () {
  94679. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  94680. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  94681. if (epsilon === void 0) { epsilon = 0.95; }
  94682. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  94683. this.edgesWidthScalerForOrthographic = 1000.0;
  94684. this.edgesWidthScalerForPerspective = 50.0;
  94685. this._linesPositions = new Array();
  94686. this._linesNormals = new Array();
  94687. this._linesIndices = new Array();
  94688. this._buffers = {};
  94689. this._checkVerticesInsteadOfIndices = false;
  94690. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  94691. this.isEnabled = true;
  94692. this._source = source;
  94693. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  94694. this._epsilon = epsilon;
  94695. this._prepareRessources();
  94696. this._generateEdgesLines();
  94697. }
  94698. EdgesRenderer.prototype._prepareRessources = function () {
  94699. if (this._lineShader) {
  94700. return;
  94701. }
  94702. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  94703. attributes: ["position", "normal"],
  94704. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  94705. });
  94706. this._lineShader.disableDepthWrite = true;
  94707. this._lineShader.backFaceCulling = false;
  94708. };
  94709. EdgesRenderer.prototype._rebuild = function () {
  94710. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94711. if (buffer) {
  94712. buffer._rebuild();
  94713. }
  94714. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94715. if (buffer) {
  94716. buffer._rebuild();
  94717. }
  94718. var scene = this._source.getScene();
  94719. var engine = scene.getEngine();
  94720. this._ib = engine.createIndexBuffer(this._linesIndices);
  94721. };
  94722. EdgesRenderer.prototype.dispose = function () {
  94723. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  94724. if (buffer) {
  94725. buffer.dispose();
  94726. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  94727. }
  94728. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  94729. if (buffer) {
  94730. buffer.dispose();
  94731. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  94732. }
  94733. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  94734. this._lineShader.dispose();
  94735. };
  94736. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  94737. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  94738. return 0;
  94739. }
  94740. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  94741. return 1;
  94742. }
  94743. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  94744. return 2;
  94745. }
  94746. return -1;
  94747. };
  94748. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  94749. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  94750. return 0;
  94751. }
  94752. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  94753. return 1;
  94754. }
  94755. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  94756. return 2;
  94757. }
  94758. return -1;
  94759. };
  94760. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  94761. var needToCreateLine;
  94762. if (edge === undefined) {
  94763. needToCreateLine = true;
  94764. }
  94765. else {
  94766. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  94767. needToCreateLine = dotProduct < this._epsilon;
  94768. }
  94769. if (needToCreateLine) {
  94770. var offset = this._linesPositions.length / 3;
  94771. var normal = p0.subtract(p1);
  94772. normal.normalize();
  94773. // Positions
  94774. this._linesPositions.push(p0.x);
  94775. this._linesPositions.push(p0.y);
  94776. this._linesPositions.push(p0.z);
  94777. this._linesPositions.push(p0.x);
  94778. this._linesPositions.push(p0.y);
  94779. this._linesPositions.push(p0.z);
  94780. this._linesPositions.push(p1.x);
  94781. this._linesPositions.push(p1.y);
  94782. this._linesPositions.push(p1.z);
  94783. this._linesPositions.push(p1.x);
  94784. this._linesPositions.push(p1.y);
  94785. this._linesPositions.push(p1.z);
  94786. // Normals
  94787. this._linesNormals.push(p1.x);
  94788. this._linesNormals.push(p1.y);
  94789. this._linesNormals.push(p1.z);
  94790. this._linesNormals.push(-1);
  94791. this._linesNormals.push(p1.x);
  94792. this._linesNormals.push(p1.y);
  94793. this._linesNormals.push(p1.z);
  94794. this._linesNormals.push(1);
  94795. this._linesNormals.push(p0.x);
  94796. this._linesNormals.push(p0.y);
  94797. this._linesNormals.push(p0.z);
  94798. this._linesNormals.push(-1);
  94799. this._linesNormals.push(p0.x);
  94800. this._linesNormals.push(p0.y);
  94801. this._linesNormals.push(p0.z);
  94802. this._linesNormals.push(1);
  94803. // Indices
  94804. this._linesIndices.push(offset);
  94805. this._linesIndices.push(offset + 1);
  94806. this._linesIndices.push(offset + 2);
  94807. this._linesIndices.push(offset);
  94808. this._linesIndices.push(offset + 2);
  94809. this._linesIndices.push(offset + 3);
  94810. }
  94811. };
  94812. EdgesRenderer.prototype._generateEdgesLines = function () {
  94813. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94814. var indices = this._source.getIndices();
  94815. if (!indices || !positions) {
  94816. return;
  94817. }
  94818. // First let's find adjacencies
  94819. var adjacencies = new Array();
  94820. var faceNormals = new Array();
  94821. var index;
  94822. var faceAdjacencies;
  94823. // Prepare faces
  94824. for (index = 0; index < indices.length; index += 3) {
  94825. faceAdjacencies = new FaceAdjacencies();
  94826. var p0Index = indices[index];
  94827. var p1Index = indices[index + 1];
  94828. var p2Index = indices[index + 2];
  94829. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  94830. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  94831. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  94832. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  94833. faceNormal.normalize();
  94834. faceNormals.push(faceNormal);
  94835. adjacencies.push(faceAdjacencies);
  94836. }
  94837. // Scan
  94838. for (index = 0; index < adjacencies.length; index++) {
  94839. faceAdjacencies = adjacencies[index];
  94840. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  94841. var otherFaceAdjacencies = adjacencies[otherIndex];
  94842. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  94843. break;
  94844. }
  94845. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  94846. continue;
  94847. }
  94848. var otherP0 = indices[otherIndex * 3];
  94849. var otherP1 = indices[otherIndex * 3 + 1];
  94850. var otherP2 = indices[otherIndex * 3 + 2];
  94851. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  94852. var otherEdgeIndex = 0;
  94853. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  94854. continue;
  94855. }
  94856. switch (edgeIndex) {
  94857. case 0:
  94858. if (this._checkVerticesInsteadOfIndices) {
  94859. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94860. }
  94861. else {
  94862. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  94863. }
  94864. break;
  94865. case 1:
  94866. if (this._checkVerticesInsteadOfIndices) {
  94867. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94868. }
  94869. else {
  94870. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  94871. }
  94872. break;
  94873. case 2:
  94874. if (this._checkVerticesInsteadOfIndices) {
  94875. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  94876. }
  94877. else {
  94878. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  94879. }
  94880. break;
  94881. }
  94882. if (otherEdgeIndex === -1) {
  94883. continue;
  94884. }
  94885. faceAdjacencies.edges[edgeIndex] = otherIndex;
  94886. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  94887. faceAdjacencies.edgesConnectedCount++;
  94888. otherFaceAdjacencies.edgesConnectedCount++;
  94889. if (faceAdjacencies.edgesConnectedCount === 3) {
  94890. break;
  94891. }
  94892. }
  94893. }
  94894. }
  94895. // Create lines
  94896. for (index = 0; index < adjacencies.length; index++) {
  94897. // 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
  94898. var current = adjacencies[index];
  94899. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  94900. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  94901. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  94902. }
  94903. // Merge into a single mesh
  94904. var engine = this._source.getScene().getEngine();
  94905. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  94906. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  94907. this._ib = engine.createIndexBuffer(this._linesIndices);
  94908. this._indicesCount = this._linesIndices.length;
  94909. };
  94910. EdgesRenderer.prototype.render = function () {
  94911. var scene = this._source.getScene();
  94912. if (!this._lineShader.isReady() || !scene.activeCamera) {
  94913. return;
  94914. }
  94915. var engine = scene.getEngine();
  94916. this._lineShader._preBind();
  94917. // VBOs
  94918. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  94919. scene.resetCachedMaterial();
  94920. this._lineShader.setColor4("color", this._source.edgesColor);
  94921. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  94922. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  94923. }
  94924. else {
  94925. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  94926. }
  94927. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  94928. this._lineShader.bind(this._source.getWorldMatrix());
  94929. // Draw order
  94930. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  94931. this._lineShader.unbind();
  94932. engine.setDepthWrite(true);
  94933. };
  94934. return EdgesRenderer;
  94935. }());
  94936. BABYLON.EdgesRenderer = EdgesRenderer;
  94937. })(BABYLON || (BABYLON = {}));
  94938. //# sourceMappingURL=babylon.edgesRenderer.js.map
  94939. var __assign = (this && this.__assign) || Object.assign || function(t) {
  94940. for (var s, i = 1, n = arguments.length; i < n; i++) {
  94941. s = arguments[i];
  94942. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  94943. t[p] = s[p];
  94944. }
  94945. return t;
  94946. };
  94947. var BABYLON;
  94948. (function (BABYLON) {
  94949. /**
  94950. * The effect layer Helps adding post process effect blended with the main pass.
  94951. *
  94952. * This can be for instance use to generate glow or higlight effects on the scene.
  94953. *
  94954. * The effect layer class can not be used directly and is intented to inherited from to be
  94955. * customized per effects.
  94956. */
  94957. var EffectLayer = /** @class */ (function () {
  94958. /**
  94959. * Instantiates a new effect Layer and references it in the scene.
  94960. * @param name The name of the layer
  94961. * @param scene The scene to use the layer in
  94962. */
  94963. function EffectLayer(
  94964. /** The Friendly of the effect in the scene */
  94965. name, scene) {
  94966. this._vertexBuffers = {};
  94967. this._maxSize = 0;
  94968. this._mainTextureDesiredSize = { width: 0, height: 0 };
  94969. this._shouldRender = true;
  94970. this._postProcesses = [];
  94971. this._textures = [];
  94972. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  94973. /**
  94974. * The clear color of the texture used to generate the glow map.
  94975. */
  94976. this.neutralColor = new BABYLON.Color4();
  94977. /**
  94978. * Specifies wether the highlight layer is enabled or not.
  94979. */
  94980. this.isEnabled = true;
  94981. /**
  94982. * An event triggered when the effect layer has been disposed.
  94983. */
  94984. this.onDisposeObservable = new BABYLON.Observable();
  94985. /**
  94986. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  94987. */
  94988. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  94989. /**
  94990. * An event triggered when the generated texture is being merged in the scene.
  94991. */
  94992. this.onBeforeComposeObservable = new BABYLON.Observable();
  94993. /**
  94994. * An event triggered when the generated texture has been merged in the scene.
  94995. */
  94996. this.onAfterComposeObservable = new BABYLON.Observable();
  94997. /**
  94998. * An event triggered when the efffect layer changes its size.
  94999. */
  95000. this.onSizeChangedObservable = new BABYLON.Observable();
  95001. this.name = name;
  95002. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95003. this._engine = scene.getEngine();
  95004. this._maxSize = this._engine.getCaps().maxTextureSize;
  95005. this._scene.effectLayers.push(this);
  95006. // Generate Buffers
  95007. this._generateIndexBuffer();
  95008. this._genrateVertexBuffer();
  95009. }
  95010. Object.defineProperty(EffectLayer.prototype, "camera", {
  95011. /**
  95012. * Gets the camera attached to the layer.
  95013. */
  95014. get: function () {
  95015. return this._effectLayerOptions.camera;
  95016. },
  95017. enumerable: true,
  95018. configurable: true
  95019. });
  95020. /**
  95021. * Initializes the effect layer with the required options.
  95022. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95023. */
  95024. EffectLayer.prototype._init = function (options) {
  95025. // Adapt options
  95026. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95027. this._setMainTextureSize();
  95028. this._createMainTexture();
  95029. this._createTextureAndPostProcesses();
  95030. this._mergeEffect = this._createMergeEffect();
  95031. };
  95032. /**
  95033. * Generates the index buffer of the full screen quad blending to the main canvas.
  95034. */
  95035. EffectLayer.prototype._generateIndexBuffer = function () {
  95036. // Indices
  95037. var indices = [];
  95038. indices.push(0);
  95039. indices.push(1);
  95040. indices.push(2);
  95041. indices.push(0);
  95042. indices.push(2);
  95043. indices.push(3);
  95044. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95045. };
  95046. /**
  95047. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95048. */
  95049. EffectLayer.prototype._genrateVertexBuffer = function () {
  95050. // VBO
  95051. var vertices = [];
  95052. vertices.push(1, 1);
  95053. vertices.push(-1, 1);
  95054. vertices.push(-1, -1);
  95055. vertices.push(1, -1);
  95056. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95057. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95058. };
  95059. /**
  95060. * Sets the main texture desired size which is the closest power of two
  95061. * of the engine canvas size.
  95062. */
  95063. EffectLayer.prototype._setMainTextureSize = function () {
  95064. if (this._effectLayerOptions.mainTextureFixedSize) {
  95065. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95066. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95067. }
  95068. else {
  95069. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95070. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95071. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95072. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95073. }
  95074. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95075. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95076. };
  95077. /**
  95078. * Creates the main texture for the effect layer.
  95079. */
  95080. EffectLayer.prototype._createMainTexture = function () {
  95081. var _this = this;
  95082. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95083. width: this._mainTextureDesiredSize.width,
  95084. height: this._mainTextureDesiredSize.height
  95085. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95086. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95087. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95088. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95089. this._mainTexture.anisotropicFilteringLevel = 1;
  95090. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95091. this._mainTexture.renderParticles = false;
  95092. this._mainTexture.renderList = null;
  95093. this._mainTexture.ignoreCameraViewport = true;
  95094. // Custom render function
  95095. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95096. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95097. var index;
  95098. var engine = _this._scene.getEngine();
  95099. if (depthOnlySubMeshes.length) {
  95100. engine.setColorWrite(false);
  95101. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95102. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95103. }
  95104. engine.setColorWrite(true);
  95105. }
  95106. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95107. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95108. }
  95109. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95110. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95111. }
  95112. for (index = 0; index < transparentSubMeshes.length; index++) {
  95113. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95114. }
  95115. };
  95116. this._mainTexture.onClearObservable.add(function (engine) {
  95117. engine.clear(_this.neutralColor, true, true, true);
  95118. });
  95119. };
  95120. /**
  95121. * Checks for the readiness of the element composing the layer.
  95122. * @param subMesh the mesh to check for
  95123. * @param useInstances specify wether or not to use instances to render the mesh
  95124. * @param emissiveTexture the associated emissive texture used to generate the glow
  95125. * @return true if ready otherwise, false
  95126. */
  95127. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95128. var material = subMesh.getMaterial();
  95129. if (!material) {
  95130. return false;
  95131. }
  95132. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95133. return false;
  95134. }
  95135. var defines = [];
  95136. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95137. var mesh = subMesh.getMesh();
  95138. var uv1 = false;
  95139. var uv2 = false;
  95140. // Alpha test
  95141. if (material && material.needAlphaTesting()) {
  95142. var alphaTexture = material.getAlphaTestTexture();
  95143. if (alphaTexture) {
  95144. defines.push("#define ALPHATEST");
  95145. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95146. alphaTexture.coordinatesIndex === 1) {
  95147. defines.push("#define DIFFUSEUV2");
  95148. uv2 = true;
  95149. }
  95150. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95151. defines.push("#define DIFFUSEUV1");
  95152. uv1 = true;
  95153. }
  95154. }
  95155. }
  95156. // Emissive
  95157. if (emissiveTexture) {
  95158. defines.push("#define EMISSIVE");
  95159. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95160. emissiveTexture.coordinatesIndex === 1) {
  95161. defines.push("#define EMISSIVEUV2");
  95162. uv2 = true;
  95163. }
  95164. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95165. defines.push("#define EMISSIVEUV1");
  95166. uv1 = true;
  95167. }
  95168. }
  95169. if (uv1) {
  95170. attribs.push(BABYLON.VertexBuffer.UVKind);
  95171. defines.push("#define UV1");
  95172. }
  95173. if (uv2) {
  95174. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95175. defines.push("#define UV2");
  95176. }
  95177. // Bones
  95178. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95181. if (mesh.numBoneInfluencers > 4) {
  95182. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95183. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95184. }
  95185. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95186. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95187. }
  95188. else {
  95189. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95190. }
  95191. // Morph targets
  95192. var manager = mesh.morphTargetManager;
  95193. var morphInfluencers = 0;
  95194. if (manager) {
  95195. if (manager.numInfluencers > 0) {
  95196. defines.push("#define MORPHTARGETS");
  95197. morphInfluencers = manager.numInfluencers;
  95198. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95199. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95200. }
  95201. }
  95202. // Instances
  95203. if (useInstances) {
  95204. defines.push("#define INSTANCES");
  95205. attribs.push("world0");
  95206. attribs.push("world1");
  95207. attribs.push("world2");
  95208. attribs.push("world3");
  95209. }
  95210. // Get correct effect
  95211. var join = defines.join("\n");
  95212. if (this._cachedDefines !== join) {
  95213. this._cachedDefines = join;
  95214. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95215. }
  95216. return this._effectLayerMapGenerationEffect.isReady();
  95217. };
  95218. /**
  95219. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95220. */
  95221. EffectLayer.prototype.render = function () {
  95222. var currentEffect = this._mergeEffect;
  95223. // Check
  95224. if (!currentEffect.isReady())
  95225. return;
  95226. for (var i = 0; i < this._postProcesses.length; i++) {
  95227. if (!this._postProcesses[i].isReady()) {
  95228. return;
  95229. }
  95230. }
  95231. var engine = this._scene.getEngine();
  95232. this.onBeforeComposeObservable.notifyObservers(this);
  95233. // Render
  95234. engine.enableEffect(currentEffect);
  95235. engine.setState(false);
  95236. // VBOs
  95237. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95238. // Cache
  95239. var previousAlphaMode = engine.getAlphaMode();
  95240. // Go Blend.
  95241. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95242. // Blends the map on the main canvas.
  95243. this._internalRender(currentEffect);
  95244. // Restore Alpha
  95245. engine.setAlphaMode(previousAlphaMode);
  95246. this.onAfterComposeObservable.notifyObservers(this);
  95247. // Handle size changes.
  95248. var size = this._mainTexture.getSize();
  95249. this._setMainTextureSize();
  95250. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95251. // Recreate RTT and post processes on size change.
  95252. this.onSizeChangedObservable.notifyObservers(this);
  95253. this._disposeTextureAndPostProcesses();
  95254. this._createMainTexture();
  95255. this._createTextureAndPostProcesses();
  95256. }
  95257. };
  95258. /**
  95259. * Determine if a given mesh will be used in the current effect.
  95260. * @param mesh mesh to test
  95261. * @returns true if the mesh will be used
  95262. */
  95263. EffectLayer.prototype.hasMesh = function (mesh) {
  95264. return true;
  95265. };
  95266. /**
  95267. * Returns true if the layer contains information to display, otherwise false.
  95268. * @returns true if the glow layer should be rendered
  95269. */
  95270. EffectLayer.prototype.shouldRender = function () {
  95271. return this.isEnabled && this._shouldRender;
  95272. };
  95273. /**
  95274. * Returns true if the mesh should render, otherwise false.
  95275. * @param mesh The mesh to render
  95276. * @returns true if it should render otherwise false
  95277. */
  95278. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95279. return true;
  95280. };
  95281. /**
  95282. * Returns true if the mesh should render, otherwise false.
  95283. * @param mesh The mesh to render
  95284. * @returns true if it should render otherwise false
  95285. */
  95286. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95287. return true;
  95288. };
  95289. /**
  95290. * Renders the submesh passed in parameter to the generation map.
  95291. */
  95292. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95293. var _this = this;
  95294. if (!this.shouldRender()) {
  95295. return;
  95296. }
  95297. var material = subMesh.getMaterial();
  95298. var mesh = subMesh.getRenderingMesh();
  95299. var scene = this._scene;
  95300. var engine = scene.getEngine();
  95301. if (!material) {
  95302. return;
  95303. }
  95304. // Do not block in blend mode.
  95305. if (material.needAlphaBlendingForMesh(mesh)) {
  95306. return;
  95307. }
  95308. // Culling
  95309. engine.setState(material.backFaceCulling);
  95310. // Managing instances
  95311. var batch = mesh._getInstancesRenderList(subMesh._id);
  95312. if (batch.mustReturn) {
  95313. return;
  95314. }
  95315. // Early Exit per mesh
  95316. if (!this._shouldRenderMesh(mesh)) {
  95317. return;
  95318. }
  95319. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95320. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95321. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95322. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95323. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95324. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95325. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95326. // Alpha test
  95327. if (material && material.needAlphaTesting()) {
  95328. var alphaTexture = material.getAlphaTestTexture();
  95329. if (alphaTexture) {
  95330. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95331. var textureMatrix = alphaTexture.getTextureMatrix();
  95332. if (textureMatrix) {
  95333. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95334. }
  95335. }
  95336. }
  95337. // Glow emissive only
  95338. if (this._emissiveTextureAndColor.texture) {
  95339. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95340. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95341. }
  95342. // Bones
  95343. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95344. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95345. }
  95346. // Morph targets
  95347. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95348. // Draw
  95349. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95350. }
  95351. else {
  95352. // Need to reset refresh rate of the shadowMap
  95353. this._mainTexture.resetRefreshCounter();
  95354. }
  95355. };
  95356. /**
  95357. * Rebuild the required buffers.
  95358. * @hidden Internal use only.
  95359. */
  95360. EffectLayer.prototype._rebuild = function () {
  95361. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95362. if (vb) {
  95363. vb._rebuild();
  95364. }
  95365. this._generateIndexBuffer();
  95366. };
  95367. /**
  95368. * Dispose only the render target textures and post process.
  95369. */
  95370. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95371. this._mainTexture.dispose();
  95372. for (var i = 0; i < this._postProcesses.length; i++) {
  95373. if (this._postProcesses[i]) {
  95374. this._postProcesses[i].dispose();
  95375. }
  95376. }
  95377. this._postProcesses = [];
  95378. for (var i = 0; i < this._textures.length; i++) {
  95379. if (this._textures[i]) {
  95380. this._textures[i].dispose();
  95381. }
  95382. }
  95383. this._textures = [];
  95384. };
  95385. /**
  95386. * Dispose the highlight layer and free resources.
  95387. */
  95388. EffectLayer.prototype.dispose = function () {
  95389. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95390. if (vertexBuffer) {
  95391. vertexBuffer.dispose();
  95392. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  95393. }
  95394. if (this._indexBuffer) {
  95395. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  95396. this._indexBuffer = null;
  95397. }
  95398. // Clean textures and post processes
  95399. this._disposeTextureAndPostProcesses();
  95400. // Remove from scene
  95401. var index = this._scene.effectLayers.indexOf(this, 0);
  95402. if (index > -1) {
  95403. this._scene.effectLayers.splice(index, 1);
  95404. }
  95405. // Callback
  95406. this.onDisposeObservable.notifyObservers(this);
  95407. this.onDisposeObservable.clear();
  95408. this.onBeforeRenderMainTextureObservable.clear();
  95409. this.onBeforeComposeObservable.clear();
  95410. this.onAfterComposeObservable.clear();
  95411. this.onSizeChangedObservable.clear();
  95412. };
  95413. /**
  95414. * Gets the class name of the effect layer
  95415. * @returns the string with the class name of the effect layer
  95416. */
  95417. EffectLayer.prototype.getClassName = function () {
  95418. return "EffectLayer";
  95419. };
  95420. /**
  95421. * Creates an effect layer from parsed effect layer data
  95422. * @param parsedEffectLayer defines effect layer data
  95423. * @param scene defines the current scene
  95424. * @param rootUrl defines the root URL containing the effect layer information
  95425. * @returns a parsed effect Layer
  95426. */
  95427. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  95428. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  95429. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  95430. };
  95431. __decorate([
  95432. BABYLON.serialize()
  95433. ], EffectLayer.prototype, "name", void 0);
  95434. __decorate([
  95435. BABYLON.serializeAsColor4()
  95436. ], EffectLayer.prototype, "neutralColor", void 0);
  95437. __decorate([
  95438. BABYLON.serialize()
  95439. ], EffectLayer.prototype, "isEnabled", void 0);
  95440. __decorate([
  95441. BABYLON.serializeAsCameraReference()
  95442. ], EffectLayer.prototype, "camera", null);
  95443. return EffectLayer;
  95444. }());
  95445. BABYLON.EffectLayer = EffectLayer;
  95446. })(BABYLON || (BABYLON = {}));
  95447. //# sourceMappingURL=babylon.effectLayer.js.map
  95448. var BABYLON;
  95449. (function (BABYLON) {
  95450. /**
  95451. * Special Glow Blur post process only blurring the alpha channel
  95452. * It enforces keeping the most luminous color in the color channel.
  95453. */
  95454. var GlowBlurPostProcess = /** @class */ (function (_super) {
  95455. __extends(GlowBlurPostProcess, _super);
  95456. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  95457. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  95458. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  95459. _this.direction = direction;
  95460. _this.kernel = kernel;
  95461. _this.onApplyObservable.add(function (effect) {
  95462. effect.setFloat2("screenSize", _this.width, _this.height);
  95463. effect.setVector2("direction", _this.direction);
  95464. effect.setFloat("blurWidth", _this.kernel);
  95465. });
  95466. return _this;
  95467. }
  95468. return GlowBlurPostProcess;
  95469. }(BABYLON.PostProcess));
  95470. /**
  95471. * The highlight layer Helps adding a glow effect around a mesh.
  95472. *
  95473. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  95474. * glowy meshes to your scene.
  95475. *
  95476. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  95477. */
  95478. var HighlightLayer = /** @class */ (function (_super) {
  95479. __extends(HighlightLayer, _super);
  95480. /**
  95481. * Instantiates a new highlight Layer and references it to the scene..
  95482. * @param name The name of the layer
  95483. * @param scene The scene to use the layer in
  95484. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  95485. */
  95486. function HighlightLayer(name, scene, options) {
  95487. var _this = _super.call(this, name, scene) || this;
  95488. _this.name = name;
  95489. /**
  95490. * Specifies whether or not the inner glow is ACTIVE in the layer.
  95491. */
  95492. _this.innerGlow = true;
  95493. /**
  95494. * Specifies whether or not the outer glow is ACTIVE in the layer.
  95495. */
  95496. _this.outerGlow = true;
  95497. /**
  95498. * An event triggered when the highlight layer is being blurred.
  95499. */
  95500. _this.onBeforeBlurObservable = new BABYLON.Observable();
  95501. /**
  95502. * An event triggered when the highlight layer has been blurred.
  95503. */
  95504. _this.onAfterBlurObservable = new BABYLON.Observable();
  95505. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  95506. _this._meshes = {};
  95507. _this._excludedMeshes = {};
  95508. _this.neutralColor = HighlightLayer.NeutralColor;
  95509. // Warn on stencil
  95510. if (!_this._engine.isStencilEnable) {
  95511. 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 }");
  95512. }
  95513. // Adapt options
  95514. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95515. // Initialize the layer
  95516. _this._init({
  95517. alphaBlendingMode: _this._options.alphaBlendingMode,
  95518. camera: _this._options.camera,
  95519. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  95520. mainTextureRatio: _this._options.mainTextureRatio
  95521. });
  95522. // Do not render as long as no meshes have been added
  95523. _this._shouldRender = false;
  95524. return _this;
  95525. }
  95526. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  95527. /**
  95528. * Gets the horizontal size of the blur.
  95529. */
  95530. get: function () {
  95531. return this._horizontalBlurPostprocess.kernel;
  95532. },
  95533. /**
  95534. * Specifies the horizontal size of the blur.
  95535. */
  95536. set: function (value) {
  95537. this._horizontalBlurPostprocess.kernel = value;
  95538. },
  95539. enumerable: true,
  95540. configurable: true
  95541. });
  95542. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  95543. /**
  95544. * Gets the vertical size of the blur.
  95545. */
  95546. get: function () {
  95547. return this._verticalBlurPostprocess.kernel;
  95548. },
  95549. /**
  95550. * Specifies the vertical size of the blur.
  95551. */
  95552. set: function (value) {
  95553. this._verticalBlurPostprocess.kernel = value;
  95554. },
  95555. enumerable: true,
  95556. configurable: true
  95557. });
  95558. /**
  95559. * Get the effect name of the layer.
  95560. * @return The effect name
  95561. */
  95562. HighlightLayer.prototype.getEffectName = function () {
  95563. return HighlightLayer.EffectName;
  95564. };
  95565. /**
  95566. * Create the merge effect. This is the shader use to blit the information back
  95567. * to the main canvas at the end of the scene rendering.
  95568. */
  95569. HighlightLayer.prototype._createMergeEffect = function () {
  95570. // Effect
  95571. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  95572. };
  95573. /**
  95574. * Creates the render target textures and post processes used in the highlight layer.
  95575. */
  95576. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  95577. var _this = this;
  95578. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  95579. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  95580. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  95581. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  95582. var textureType = 0;
  95583. if (this._engine.getCaps().textureHalfFloatRender) {
  95584. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  95585. }
  95586. else {
  95587. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95588. }
  95589. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  95590. width: blurTextureWidth,
  95591. height: blurTextureHeight
  95592. }, this._scene, false, true, textureType);
  95593. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95594. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95595. this._blurTexture.anisotropicFilteringLevel = 16;
  95596. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  95597. this._blurTexture.renderParticles = false;
  95598. this._blurTexture.ignoreCameraViewport = true;
  95599. this._textures = [this._blurTexture];
  95600. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  95601. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95602. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  95603. effect.setTexture("textureSampler", _this._mainTexture);
  95604. });
  95605. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95606. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95607. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95608. });
  95609. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  95610. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  95611. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  95612. });
  95613. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95614. }
  95615. else {
  95616. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  95617. width: blurTextureWidth,
  95618. height: blurTextureHeight
  95619. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95620. this._horizontalBlurPostprocess.width = blurTextureWidth;
  95621. this._horizontalBlurPostprocess.height = blurTextureHeight;
  95622. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  95623. effect.setTexture("textureSampler", _this._mainTexture);
  95624. });
  95625. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  95626. width: blurTextureWidth,
  95627. height: blurTextureHeight
  95628. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  95629. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  95630. }
  95631. this._mainTexture.onAfterUnbindObservable.add(function () {
  95632. _this.onBeforeBlurObservable.notifyObservers(_this);
  95633. var internalTexture = _this._blurTexture.getInternalTexture();
  95634. if (internalTexture) {
  95635. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  95636. }
  95637. _this.onAfterBlurObservable.notifyObservers(_this);
  95638. });
  95639. // Prevent autoClear.
  95640. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  95641. };
  95642. /**
  95643. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  95644. */
  95645. HighlightLayer.prototype.needStencil = function () {
  95646. return true;
  95647. };
  95648. /**
  95649. * Checks for the readiness of the element composing the layer.
  95650. * @param subMesh the mesh to check for
  95651. * @param useInstances specify wether or not to use instances to render the mesh
  95652. * @param emissiveTexture the associated emissive texture used to generate the glow
  95653. * @return true if ready otherwise, false
  95654. */
  95655. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  95656. var material = subMesh.getMaterial();
  95657. var mesh = subMesh.getRenderingMesh();
  95658. if (!material || !mesh || !this._meshes) {
  95659. return false;
  95660. }
  95661. var emissiveTexture = null;
  95662. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95663. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95664. emissiveTexture = material.emissiveTexture;
  95665. }
  95666. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  95667. };
  95668. /**
  95669. * Implementation specific of rendering the generating effect on the main canvas.
  95670. * @param effect The effect used to render through
  95671. */
  95672. HighlightLayer.prototype._internalRender = function (effect) {
  95673. // Texture
  95674. effect.setTexture("textureSampler", this._blurTexture);
  95675. // Cache
  95676. var engine = this._engine;
  95677. var previousStencilBuffer = engine.getStencilBuffer();
  95678. var previousStencilFunction = engine.getStencilFunction();
  95679. var previousStencilMask = engine.getStencilMask();
  95680. var previousStencilOperationPass = engine.getStencilOperationPass();
  95681. var previousStencilOperationFail = engine.getStencilOperationFail();
  95682. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  95683. var previousStencilReference = engine.getStencilFunctionReference();
  95684. // Stencil operations
  95685. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  95686. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  95687. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  95688. // Draw order
  95689. engine.setStencilMask(0x00);
  95690. engine.setStencilBuffer(true);
  95691. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  95692. // 2 passes inner outer
  95693. if (this.outerGlow) {
  95694. effect.setFloat("offset", 0);
  95695. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  95696. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95697. }
  95698. if (this.innerGlow) {
  95699. effect.setFloat("offset", 1);
  95700. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  95701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  95702. }
  95703. // Restore Cache
  95704. engine.setStencilFunction(previousStencilFunction);
  95705. engine.setStencilMask(previousStencilMask);
  95706. engine.setStencilBuffer(previousStencilBuffer);
  95707. engine.setStencilOperationPass(previousStencilOperationPass);
  95708. engine.setStencilOperationFail(previousStencilOperationFail);
  95709. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  95710. engine.setStencilFunctionReference(previousStencilReference);
  95711. };
  95712. /**
  95713. * Returns true if the layer contains information to display, otherwise false.
  95714. */
  95715. HighlightLayer.prototype.shouldRender = function () {
  95716. if (_super.prototype.shouldRender.call(this)) {
  95717. return this._meshes ? true : false;
  95718. }
  95719. return false;
  95720. };
  95721. /**
  95722. * Returns true if the mesh should render, otherwise false.
  95723. * @param mesh The mesh to render
  95724. * @returns true if it should render otherwise false
  95725. */
  95726. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  95727. // Excluded Mesh
  95728. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  95729. return false;
  95730. }
  95731. ;
  95732. return true;
  95733. };
  95734. /**
  95735. * Sets the required values for both the emissive texture and and the main color.
  95736. */
  95737. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  95738. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  95739. if (highlightLayerMesh) {
  95740. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  95741. }
  95742. else {
  95743. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  95744. }
  95745. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  95746. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  95747. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  95748. }
  95749. else {
  95750. this._emissiveTextureAndColor.texture = null;
  95751. }
  95752. };
  95753. /**
  95754. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  95755. * @param mesh The mesh to exclude from the highlight layer
  95756. */
  95757. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  95758. if (!this._excludedMeshes) {
  95759. return;
  95760. }
  95761. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95762. if (!meshExcluded) {
  95763. this._excludedMeshes[mesh.uniqueId] = {
  95764. mesh: mesh,
  95765. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  95766. mesh.getEngine().setStencilBuffer(false);
  95767. }),
  95768. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  95769. mesh.getEngine().setStencilBuffer(true);
  95770. }),
  95771. };
  95772. }
  95773. };
  95774. /**
  95775. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  95776. * @param mesh The mesh to highlight
  95777. */
  95778. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  95779. if (!this._excludedMeshes) {
  95780. return;
  95781. }
  95782. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  95783. if (meshExcluded) {
  95784. if (meshExcluded.beforeRender) {
  95785. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  95786. }
  95787. if (meshExcluded.afterRender) {
  95788. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  95789. }
  95790. }
  95791. this._excludedMeshes[mesh.uniqueId] = null;
  95792. };
  95793. /**
  95794. * Determine if a given mesh will be highlighted by the current HighlightLayer
  95795. * @param mesh mesh to test
  95796. * @returns true if the mesh will be highlighted by the current HighlightLayer
  95797. */
  95798. HighlightLayer.prototype.hasMesh = function (mesh) {
  95799. if (!this._meshes) {
  95800. return false;
  95801. }
  95802. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  95803. };
  95804. /**
  95805. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  95806. * @param mesh The mesh to highlight
  95807. * @param color The color of the highlight
  95808. * @param glowEmissiveOnly Extract the glow from the emissive texture
  95809. */
  95810. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  95811. var _this = this;
  95812. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  95813. if (!this._meshes) {
  95814. return;
  95815. }
  95816. var meshHighlight = this._meshes[mesh.uniqueId];
  95817. if (meshHighlight) {
  95818. meshHighlight.color = color;
  95819. }
  95820. else {
  95821. this._meshes[mesh.uniqueId] = {
  95822. mesh: mesh,
  95823. color: color,
  95824. // Lambda required for capture due to Observable this context
  95825. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  95826. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  95827. _this._defaultStencilReference(mesh);
  95828. }
  95829. else {
  95830. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  95831. }
  95832. }),
  95833. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  95834. glowEmissiveOnly: glowEmissiveOnly
  95835. };
  95836. }
  95837. this._shouldRender = true;
  95838. };
  95839. /**
  95840. * Remove a mesh from the highlight layer in order to make it stop glowing.
  95841. * @param mesh The mesh to highlight
  95842. */
  95843. HighlightLayer.prototype.removeMesh = function (mesh) {
  95844. if (!this._meshes) {
  95845. return;
  95846. }
  95847. var meshHighlight = this._meshes[mesh.uniqueId];
  95848. if (meshHighlight) {
  95849. if (meshHighlight.observerHighlight) {
  95850. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95851. }
  95852. if (meshHighlight.observerDefault) {
  95853. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95854. }
  95855. delete this._meshes[mesh.uniqueId];
  95856. }
  95857. this._shouldRender = false;
  95858. for (var meshHighlightToCheck in this._meshes) {
  95859. if (this._meshes[meshHighlightToCheck]) {
  95860. this._shouldRender = true;
  95861. break;
  95862. }
  95863. }
  95864. };
  95865. /**
  95866. * Force the stencil to the normal expected value for none glowing parts
  95867. */
  95868. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  95869. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  95870. };
  95871. /**
  95872. * Free any resources and references associated to a mesh.
  95873. * Internal use
  95874. * @param mesh The mesh to free.
  95875. */
  95876. HighlightLayer.prototype._disposeMesh = function (mesh) {
  95877. this.removeMesh(mesh);
  95878. this.removeExcludedMesh(mesh);
  95879. };
  95880. /**
  95881. * Dispose the highlight layer and free resources.
  95882. */
  95883. HighlightLayer.prototype.dispose = function () {
  95884. if (this._meshes) {
  95885. // Clean mesh references
  95886. for (var id in this._meshes) {
  95887. var meshHighlight = this._meshes[id];
  95888. if (meshHighlight && meshHighlight.mesh) {
  95889. if (meshHighlight.observerHighlight) {
  95890. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  95891. }
  95892. if (meshHighlight.observerDefault) {
  95893. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  95894. }
  95895. }
  95896. }
  95897. this._meshes = null;
  95898. }
  95899. if (this._excludedMeshes) {
  95900. for (var id in this._excludedMeshes) {
  95901. var meshHighlight = this._excludedMeshes[id];
  95902. if (meshHighlight) {
  95903. if (meshHighlight.beforeRender) {
  95904. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  95905. }
  95906. if (meshHighlight.afterRender) {
  95907. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  95908. }
  95909. }
  95910. }
  95911. this._excludedMeshes = null;
  95912. }
  95913. _super.prototype.dispose.call(this);
  95914. };
  95915. /**
  95916. * Gets the class name of the effect layer
  95917. * @returns the string with the class name of the effect layer
  95918. */
  95919. HighlightLayer.prototype.getClassName = function () {
  95920. return "HighlightLayer";
  95921. };
  95922. /**
  95923. * Serializes this Highlight layer
  95924. * @returns a serialized Highlight layer object
  95925. */
  95926. HighlightLayer.prototype.serialize = function () {
  95927. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  95928. serializationObject.customType = "BABYLON.HighlightLayer";
  95929. // Highlighted meshes
  95930. serializationObject.meshes = [];
  95931. if (this._meshes) {
  95932. for (var m in this._meshes) {
  95933. var mesh = this._meshes[m];
  95934. if (mesh) {
  95935. serializationObject.meshes.push({
  95936. glowEmissiveOnly: mesh.glowEmissiveOnly,
  95937. color: mesh.color.asArray(),
  95938. meshId: mesh.mesh.id
  95939. });
  95940. }
  95941. }
  95942. }
  95943. // Excluded meshes
  95944. serializationObject.excludedMeshes = [];
  95945. if (this._excludedMeshes) {
  95946. for (var e in this._excludedMeshes) {
  95947. var excludedMesh = this._excludedMeshes[e];
  95948. if (excludedMesh) {
  95949. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  95950. }
  95951. }
  95952. }
  95953. return serializationObject;
  95954. };
  95955. /**
  95956. * Creates a Highlight layer from parsed Highlight layer data
  95957. * @param parsedHightlightLayer defines the Highlight layer data
  95958. * @param scene defines the current scene
  95959. * @param rootUrl defines the root URL containing the Highlight layer information
  95960. * @returns a parsed Highlight layer
  95961. */
  95962. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  95963. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  95964. var index;
  95965. // Excluded meshes
  95966. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  95967. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  95968. if (mesh) {
  95969. hl.addExcludedMesh(mesh);
  95970. }
  95971. }
  95972. // Included meshes
  95973. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  95974. var highlightedMesh = parsedHightlightLayer.meshes[index];
  95975. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  95976. if (mesh) {
  95977. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  95978. }
  95979. }
  95980. return hl;
  95981. };
  95982. /**
  95983. * Effect Name of the highlight layer.
  95984. */
  95985. HighlightLayer.EffectName = "HighlightLayer";
  95986. /**
  95987. * The neutral color used during the preparation of the glow effect.
  95988. * This is black by default as the blend operation is a blend operation.
  95989. */
  95990. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  95991. /**
  95992. * Stencil value used for glowing meshes.
  95993. */
  95994. HighlightLayer.GlowingMeshStencilReference = 0x02;
  95995. /**
  95996. * Stencil value used for the other meshes in the scene.
  95997. */
  95998. HighlightLayer.NormalMeshStencilReference = 0x01;
  95999. __decorate([
  96000. BABYLON.serialize()
  96001. ], HighlightLayer.prototype, "innerGlow", void 0);
  96002. __decorate([
  96003. BABYLON.serialize()
  96004. ], HighlightLayer.prototype, "outerGlow", void 0);
  96005. __decorate([
  96006. BABYLON.serialize()
  96007. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96008. __decorate([
  96009. BABYLON.serialize()
  96010. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96011. __decorate([
  96012. BABYLON.serialize("options")
  96013. ], HighlightLayer.prototype, "_options", void 0);
  96014. return HighlightLayer;
  96015. }(BABYLON.EffectLayer));
  96016. BABYLON.HighlightLayer = HighlightLayer;
  96017. })(BABYLON || (BABYLON = {}));
  96018. //# sourceMappingURL=babylon.highlightLayer.js.map
  96019. var BABYLON;
  96020. (function (BABYLON) {
  96021. /**
  96022. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96023. *
  96024. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96025. * glowy meshes to your scene.
  96026. *
  96027. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96028. */
  96029. var GlowLayer = /** @class */ (function (_super) {
  96030. __extends(GlowLayer, _super);
  96031. /**
  96032. * Instantiates a new glow Layer and references it to the scene.
  96033. * @param name The name of the layer
  96034. * @param scene The scene to use the layer in
  96035. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96036. */
  96037. function GlowLayer(name, scene, options) {
  96038. var _this = _super.call(this, name, scene) || this;
  96039. _this._intensity = 1.0;
  96040. _this._includedOnlyMeshes = [];
  96041. _this._excludedMeshes = [];
  96042. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96043. // Adapt options
  96044. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96045. // Initialize the layer
  96046. _this._init({
  96047. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96048. camera: _this._options.camera,
  96049. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96050. mainTextureRatio: _this._options.mainTextureRatio
  96051. });
  96052. return _this;
  96053. }
  96054. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96055. /**
  96056. * Gets the kernel size of the blur.
  96057. */
  96058. get: function () {
  96059. return this._horizontalBlurPostprocess1.kernel;
  96060. },
  96061. /**
  96062. * Sets the kernel size of the blur.
  96063. */
  96064. set: function (value) {
  96065. this._horizontalBlurPostprocess1.kernel = value;
  96066. this._verticalBlurPostprocess1.kernel = value;
  96067. this._horizontalBlurPostprocess2.kernel = value;
  96068. this._verticalBlurPostprocess2.kernel = value;
  96069. },
  96070. enumerable: true,
  96071. configurable: true
  96072. });
  96073. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96074. /**
  96075. * Gets the glow intensity.
  96076. */
  96077. get: function () {
  96078. return this._intensity;
  96079. },
  96080. /**
  96081. * Sets the glow intensity.
  96082. */
  96083. set: function (value) {
  96084. this._intensity = value;
  96085. },
  96086. enumerable: true,
  96087. configurable: true
  96088. });
  96089. /**
  96090. * Get the effect name of the layer.
  96091. * @return The effect name
  96092. */
  96093. GlowLayer.prototype.getEffectName = function () {
  96094. return GlowLayer.EffectName;
  96095. };
  96096. /**
  96097. * Create the merge effect. This is the shader use to blit the information back
  96098. * to the main canvas at the end of the scene rendering.
  96099. */
  96100. GlowLayer.prototype._createMergeEffect = function () {
  96101. // Effect
  96102. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96103. };
  96104. /**
  96105. * Creates the render target textures and post processes used in the glow layer.
  96106. */
  96107. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96108. var _this = this;
  96109. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96110. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96111. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96112. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96113. var textureType = 0;
  96114. if (this._engine.getCaps().textureHalfFloatRender) {
  96115. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96116. }
  96117. else {
  96118. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96119. }
  96120. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96121. width: blurTextureWidth,
  96122. height: blurTextureHeight
  96123. }, this._scene, false, true, textureType);
  96124. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96125. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96126. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96127. this._blurTexture1.renderParticles = false;
  96128. this._blurTexture1.ignoreCameraViewport = true;
  96129. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96130. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96131. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96132. width: blurTextureWidth2,
  96133. height: blurTextureHeight2
  96134. }, this._scene, false, true, textureType);
  96135. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96136. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96137. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96138. this._blurTexture2.renderParticles = false;
  96139. this._blurTexture2.ignoreCameraViewport = true;
  96140. this._textures = [this._blurTexture1, this._blurTexture2];
  96141. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96142. width: blurTextureWidth,
  96143. height: blurTextureHeight
  96144. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96145. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96146. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96147. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96148. effect.setTexture("textureSampler", _this._mainTexture);
  96149. });
  96150. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96151. width: blurTextureWidth,
  96152. height: blurTextureHeight
  96153. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96154. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96155. width: blurTextureWidth2,
  96156. height: blurTextureHeight2
  96157. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96158. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96159. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96160. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96161. effect.setTexture("textureSampler", _this._blurTexture1);
  96162. });
  96163. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96164. width: blurTextureWidth2,
  96165. height: blurTextureHeight2
  96166. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96167. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96168. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96169. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96170. this._mainTexture.samples = this._options.mainTextureSamples;
  96171. this._mainTexture.onAfterUnbindObservable.add(function () {
  96172. var internalTexture = _this._blurTexture1.getInternalTexture();
  96173. if (internalTexture) {
  96174. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96175. internalTexture = _this._blurTexture2.getInternalTexture();
  96176. if (internalTexture) {
  96177. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96178. }
  96179. }
  96180. });
  96181. // Prevent autoClear.
  96182. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96183. };
  96184. /**
  96185. * Checks for the readiness of the element composing the layer.
  96186. * @param subMesh the mesh to check for
  96187. * @param useInstances specify wether or not to use instances to render the mesh
  96188. * @param emissiveTexture the associated emissive texture used to generate the glow
  96189. * @return true if ready otherwise, false
  96190. */
  96191. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96192. var material = subMesh.getMaterial();
  96193. var mesh = subMesh.getRenderingMesh();
  96194. if (!material || !mesh) {
  96195. return false;
  96196. }
  96197. var emissiveTexture = material.emissiveTexture;
  96198. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96199. };
  96200. /**
  96201. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96202. */
  96203. GlowLayer.prototype.needStencil = function () {
  96204. return false;
  96205. };
  96206. /**
  96207. * Implementation specific of rendering the generating effect on the main canvas.
  96208. * @param effect The effect used to render through
  96209. */
  96210. GlowLayer.prototype._internalRender = function (effect) {
  96211. // Texture
  96212. effect.setTexture("textureSampler", this._blurTexture1);
  96213. effect.setTexture("textureSampler2", this._blurTexture2);
  96214. effect.setFloat("offset", this._intensity);
  96215. // Cache
  96216. var engine = this._engine;
  96217. var previousStencilBuffer = engine.getStencilBuffer();
  96218. // Draw order
  96219. engine.setStencilBuffer(false);
  96220. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96221. // Draw order
  96222. engine.setStencilBuffer(previousStencilBuffer);
  96223. };
  96224. /**
  96225. * Sets the required values for both the emissive texture and and the main color.
  96226. */
  96227. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96228. var textureLevel = 1.0;
  96229. if (this.customEmissiveTextureSelector) {
  96230. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96231. }
  96232. else {
  96233. if (material) {
  96234. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96235. if (this._emissiveTextureAndColor.texture) {
  96236. textureLevel = this._emissiveTextureAndColor.texture.level;
  96237. }
  96238. }
  96239. else {
  96240. this._emissiveTextureAndColor.texture = null;
  96241. }
  96242. }
  96243. if (this.customEmissiveColorSelector) {
  96244. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96245. }
  96246. else {
  96247. if (material.emissiveColor) {
  96248. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96249. }
  96250. else {
  96251. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96252. }
  96253. }
  96254. };
  96255. /**
  96256. * Returns true if the mesh should render, otherwise false.
  96257. * @param mesh The mesh to render
  96258. * @returns true if it should render otherwise false
  96259. */
  96260. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96261. return this.hasMesh(mesh);
  96262. };
  96263. /**
  96264. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96265. * @param mesh The mesh to exclude from the glow layer
  96266. */
  96267. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96268. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96269. this._excludedMeshes.push(mesh.uniqueId);
  96270. }
  96271. };
  96272. /**
  96273. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96274. * @param mesh The mesh to remove
  96275. */
  96276. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96277. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96278. if (index !== -1) {
  96279. this._excludedMeshes.splice(index, 1);
  96280. }
  96281. };
  96282. /**
  96283. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96284. * @param mesh The mesh to include in the glow layer
  96285. */
  96286. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96287. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96288. this._includedOnlyMeshes.push(mesh.uniqueId);
  96289. }
  96290. };
  96291. /**
  96292. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96293. * @param mesh The mesh to remove
  96294. */
  96295. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96296. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96297. if (index !== -1) {
  96298. this._includedOnlyMeshes.splice(index, 1);
  96299. }
  96300. };
  96301. /**
  96302. * Determine if a given mesh will be used in the glow layer
  96303. * @param mesh The mesh to test
  96304. * @returns true if the mesh will be highlighted by the current glow layer
  96305. */
  96306. GlowLayer.prototype.hasMesh = function (mesh) {
  96307. // Included Mesh
  96308. if (this._includedOnlyMeshes.length) {
  96309. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96310. }
  96311. ;
  96312. // Excluded Mesh
  96313. if (this._excludedMeshes.length) {
  96314. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96315. }
  96316. ;
  96317. return true;
  96318. };
  96319. /**
  96320. * Free any resources and references associated to a mesh.
  96321. * Internal use
  96322. * @param mesh The mesh to free.
  96323. */
  96324. GlowLayer.prototype._disposeMesh = function (mesh) {
  96325. this.removeIncludedOnlyMesh(mesh);
  96326. this.removeExcludedMesh(mesh);
  96327. };
  96328. /**
  96329. * Gets the class name of the effect layer
  96330. * @returns the string with the class name of the effect layer
  96331. */
  96332. GlowLayer.prototype.getClassName = function () {
  96333. return "GlowLayer";
  96334. };
  96335. /**
  96336. * Serializes this glow layer
  96337. * @returns a serialized glow layer object
  96338. */
  96339. GlowLayer.prototype.serialize = function () {
  96340. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96341. serializationObject.customType = "BABYLON.GlowLayer";
  96342. var index;
  96343. // Included meshes
  96344. serializationObject.includedMeshes = [];
  96345. if (this._includedOnlyMeshes.length) {
  96346. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96347. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96348. if (mesh) {
  96349. serializationObject.includedMeshes.push(mesh.id);
  96350. }
  96351. }
  96352. }
  96353. // Excluded meshes
  96354. serializationObject.excludedMeshes = [];
  96355. if (this._excludedMeshes.length) {
  96356. for (index = 0; index < this._excludedMeshes.length; index++) {
  96357. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96358. if (mesh) {
  96359. serializationObject.excludedMeshes.push(mesh.id);
  96360. }
  96361. }
  96362. }
  96363. return serializationObject;
  96364. };
  96365. /**
  96366. * Creates a Glow Layer from parsed glow layer data
  96367. * @param parsedGlowLayer defines glow layer data
  96368. * @param scene defines the current scene
  96369. * @param rootUrl defines the root URL containing the glow layer information
  96370. * @returns a parsed Glow Layer
  96371. */
  96372. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96373. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96374. var index;
  96375. // Excluded meshes
  96376. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96377. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96378. if (mesh) {
  96379. gl.addExcludedMesh(mesh);
  96380. }
  96381. }
  96382. // Included meshes
  96383. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96384. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96385. if (mesh) {
  96386. gl.addIncludedOnlyMesh(mesh);
  96387. }
  96388. }
  96389. return gl;
  96390. };
  96391. /**
  96392. * Effect Name of the layer.
  96393. */
  96394. GlowLayer.EffectName = "GlowLayer";
  96395. /**
  96396. * The default blur kernel size used for the glow.
  96397. */
  96398. GlowLayer.DefaultBlurKernelSize = 32;
  96399. /**
  96400. * The default texture size ratio used for the glow.
  96401. */
  96402. GlowLayer.DefaultTextureRatio = 0.5;
  96403. __decorate([
  96404. BABYLON.serialize()
  96405. ], GlowLayer.prototype, "blurKernelSize", null);
  96406. __decorate([
  96407. BABYLON.serialize()
  96408. ], GlowLayer.prototype, "intensity", null);
  96409. __decorate([
  96410. BABYLON.serialize("options")
  96411. ], GlowLayer.prototype, "_options", void 0);
  96412. return GlowLayer;
  96413. }(BABYLON.EffectLayer));
  96414. BABYLON.GlowLayer = GlowLayer;
  96415. })(BABYLON || (BABYLON = {}));
  96416. //# sourceMappingURL=babylon.glowLayer.js.map
  96417. var BABYLON;
  96418. (function (BABYLON) {
  96419. /**
  96420. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  96421. */
  96422. var AssetTaskState;
  96423. (function (AssetTaskState) {
  96424. /**
  96425. * Initialization
  96426. */
  96427. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  96428. /**
  96429. * Running
  96430. */
  96431. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  96432. /**
  96433. * Done
  96434. */
  96435. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  96436. /**
  96437. * Error
  96438. */
  96439. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  96440. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  96441. /**
  96442. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  96443. */
  96444. var AbstractAssetTask = /** @class */ (function () {
  96445. /**
  96446. * Creates a new {BABYLON.AssetsManager}
  96447. * @param name defines the name of the task
  96448. */
  96449. function AbstractAssetTask(
  96450. /**
  96451. * Task name
  96452. */ name) {
  96453. this.name = name;
  96454. this._isCompleted = false;
  96455. this._taskState = AssetTaskState.INIT;
  96456. }
  96457. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  96458. /**
  96459. * Get if the task is completed
  96460. */
  96461. get: function () {
  96462. return this._isCompleted;
  96463. },
  96464. enumerable: true,
  96465. configurable: true
  96466. });
  96467. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  96468. /**
  96469. * Gets the current state of the task
  96470. */
  96471. get: function () {
  96472. return this._taskState;
  96473. },
  96474. enumerable: true,
  96475. configurable: true
  96476. });
  96477. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  96478. /**
  96479. * Gets the current error object (if task is in error)
  96480. */
  96481. get: function () {
  96482. return this._errorObject;
  96483. },
  96484. enumerable: true,
  96485. configurable: true
  96486. });
  96487. /**
  96488. * Internal only
  96489. * @hidden
  96490. */
  96491. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  96492. if (this._errorObject) {
  96493. return;
  96494. }
  96495. this._errorObject = {
  96496. message: message,
  96497. exception: exception
  96498. };
  96499. };
  96500. /**
  96501. * Execute the current task
  96502. * @param scene defines the scene where you want your assets to be loaded
  96503. * @param onSuccess is a callback called when the task is successfully executed
  96504. * @param onError is a callback called if an error occurs
  96505. */
  96506. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96507. var _this = this;
  96508. this._taskState = AssetTaskState.RUNNING;
  96509. this.runTask(scene, function () {
  96510. _this.onDoneCallback(onSuccess, onError);
  96511. }, function (msg, exception) {
  96512. _this.onErrorCallback(onError, msg, exception);
  96513. });
  96514. };
  96515. /**
  96516. * Execute the current task
  96517. * @param scene defines the scene where you want your assets to be loaded
  96518. * @param onSuccess is a callback called when the task is successfully executed
  96519. * @param onError is a callback called if an error occurs
  96520. */
  96521. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96522. throw new Error("runTask is not implemented");
  96523. };
  96524. /**
  96525. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  96526. * This can be used with failed tasks that have the reason for failure fixed.
  96527. */
  96528. AbstractAssetTask.prototype.reset = function () {
  96529. this._taskState = AssetTaskState.INIT;
  96530. };
  96531. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  96532. this._taskState = AssetTaskState.ERROR;
  96533. this._errorObject = {
  96534. message: message,
  96535. exception: exception
  96536. };
  96537. if (this.onError) {
  96538. this.onError(this, message, exception);
  96539. }
  96540. onError();
  96541. };
  96542. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  96543. try {
  96544. this._taskState = AssetTaskState.DONE;
  96545. this._isCompleted = true;
  96546. if (this.onSuccess) {
  96547. this.onSuccess(this);
  96548. }
  96549. onSuccess();
  96550. }
  96551. catch (e) {
  96552. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  96553. }
  96554. };
  96555. return AbstractAssetTask;
  96556. }());
  96557. BABYLON.AbstractAssetTask = AbstractAssetTask;
  96558. /**
  96559. * Class used to share progress information about assets loading
  96560. */
  96561. var AssetsProgressEvent = /** @class */ (function () {
  96562. /**
  96563. * Creates a {BABYLON.AssetsProgressEvent}
  96564. * @param remainingCount defines the number of remaining tasks to process
  96565. * @param totalCount defines the total number of tasks
  96566. * @param task defines the task that was just processed
  96567. */
  96568. function AssetsProgressEvent(remainingCount, totalCount, task) {
  96569. this.remainingCount = remainingCount;
  96570. this.totalCount = totalCount;
  96571. this.task = task;
  96572. }
  96573. return AssetsProgressEvent;
  96574. }());
  96575. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  96576. /**
  96577. * Define a task used by {BABYLON.AssetsManager} to load meshes
  96578. */
  96579. var MeshAssetTask = /** @class */ (function (_super) {
  96580. __extends(MeshAssetTask, _super);
  96581. /**
  96582. * Creates a new {BABYLON.MeshAssetTask}
  96583. * @param name defines the name of the task
  96584. * @param meshesNames defines the list of mesh's names you want to load
  96585. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  96586. * @param sceneFilename defines the filename of the scene to load from
  96587. */
  96588. function MeshAssetTask(
  96589. /**
  96590. * Defines the name of the task
  96591. */
  96592. name,
  96593. /**
  96594. * Defines the list of mesh's names you want to load
  96595. */
  96596. meshesNames,
  96597. /**
  96598. * Defines the root url to use as a base to load your meshes and associated resources
  96599. */
  96600. rootUrl,
  96601. /**
  96602. * Defines the filename of the scene to load from
  96603. */
  96604. sceneFilename) {
  96605. var _this = _super.call(this, name) || this;
  96606. _this.name = name;
  96607. _this.meshesNames = meshesNames;
  96608. _this.rootUrl = rootUrl;
  96609. _this.sceneFilename = sceneFilename;
  96610. return _this;
  96611. }
  96612. /**
  96613. * Execute the current task
  96614. * @param scene defines the scene where you want your assets to be loaded
  96615. * @param onSuccess is a callback called when the task is successfully executed
  96616. * @param onError is a callback called if an error occurs
  96617. */
  96618. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96619. var _this = this;
  96620. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  96621. _this.loadedMeshes = meshes;
  96622. _this.loadedParticleSystems = particleSystems;
  96623. _this.loadedSkeletons = skeletons;
  96624. onSuccess();
  96625. }, null, function (scene, message, exception) {
  96626. onError(message, exception);
  96627. });
  96628. };
  96629. return MeshAssetTask;
  96630. }(AbstractAssetTask));
  96631. BABYLON.MeshAssetTask = MeshAssetTask;
  96632. /**
  96633. * Define a task used by {BABYLON.AssetsManager} to load text content
  96634. */
  96635. var TextFileAssetTask = /** @class */ (function (_super) {
  96636. __extends(TextFileAssetTask, _super);
  96637. /**
  96638. * Creates a new TextFileAssetTask object
  96639. * @param name defines the name of the task
  96640. * @param url defines the location of the file to load
  96641. */
  96642. function TextFileAssetTask(
  96643. /**
  96644. * Defines the name of the task
  96645. */
  96646. name,
  96647. /**
  96648. * Defines the location of the file to load
  96649. */
  96650. url) {
  96651. var _this = _super.call(this, name) || this;
  96652. _this.name = name;
  96653. _this.url = url;
  96654. return _this;
  96655. }
  96656. /**
  96657. * Execute the current task
  96658. * @param scene defines the scene where you want your assets to be loaded
  96659. * @param onSuccess is a callback called when the task is successfully executed
  96660. * @param onError is a callback called if an error occurs
  96661. */
  96662. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96663. var _this = this;
  96664. scene._loadFile(this.url, function (data) {
  96665. _this.text = data;
  96666. onSuccess();
  96667. }, undefined, false, false, function (request, exception) {
  96668. if (request) {
  96669. onError(request.status + " " + request.statusText, exception);
  96670. }
  96671. });
  96672. };
  96673. return TextFileAssetTask;
  96674. }(AbstractAssetTask));
  96675. BABYLON.TextFileAssetTask = TextFileAssetTask;
  96676. /**
  96677. * Define a task used by {BABYLON.AssetsManager} to load binary data
  96678. */
  96679. var BinaryFileAssetTask = /** @class */ (function (_super) {
  96680. __extends(BinaryFileAssetTask, _super);
  96681. /**
  96682. * Creates a new BinaryFileAssetTask object
  96683. * @param name defines the name of the new task
  96684. * @param url defines the location of the file to load
  96685. */
  96686. function BinaryFileAssetTask(
  96687. /**
  96688. * Defines the name of the task
  96689. */
  96690. name,
  96691. /**
  96692. * Defines the location of the file to load
  96693. */
  96694. url) {
  96695. var _this = _super.call(this, name) || this;
  96696. _this.name = name;
  96697. _this.url = url;
  96698. return _this;
  96699. }
  96700. /**
  96701. * Execute the current task
  96702. * @param scene defines the scene where you want your assets to be loaded
  96703. * @param onSuccess is a callback called when the task is successfully executed
  96704. * @param onError is a callback called if an error occurs
  96705. */
  96706. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96707. var _this = this;
  96708. scene._loadFile(this.url, function (data) {
  96709. _this.data = data;
  96710. onSuccess();
  96711. }, undefined, true, true, function (request, exception) {
  96712. if (request) {
  96713. onError(request.status + " " + request.statusText, exception);
  96714. }
  96715. });
  96716. };
  96717. return BinaryFileAssetTask;
  96718. }(AbstractAssetTask));
  96719. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  96720. /**
  96721. * Define a task used by {BABYLON.AssetsManager} to load images
  96722. */
  96723. var ImageAssetTask = /** @class */ (function (_super) {
  96724. __extends(ImageAssetTask, _super);
  96725. /**
  96726. * Creates a new ImageAssetTask
  96727. * @param name defines the name of the task
  96728. * @param url defines the location of the image to load
  96729. */
  96730. function ImageAssetTask(
  96731. /**
  96732. * Defines the name of the task
  96733. */
  96734. name,
  96735. /**
  96736. * Defines the location of the image to load
  96737. */
  96738. url) {
  96739. var _this = _super.call(this, name) || this;
  96740. _this.name = name;
  96741. _this.url = url;
  96742. return _this;
  96743. }
  96744. /**
  96745. * Execute the current task
  96746. * @param scene defines the scene where you want your assets to be loaded
  96747. * @param onSuccess is a callback called when the task is successfully executed
  96748. * @param onError is a callback called if an error occurs
  96749. */
  96750. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96751. var _this = this;
  96752. var img = new Image();
  96753. BABYLON.Tools.SetCorsBehavior(this.url, img);
  96754. img.onload = function () {
  96755. _this.image = img;
  96756. onSuccess();
  96757. };
  96758. img.onerror = function (err) {
  96759. onError("Error loading image", err);
  96760. };
  96761. img.src = this.url;
  96762. };
  96763. return ImageAssetTask;
  96764. }(AbstractAssetTask));
  96765. BABYLON.ImageAssetTask = ImageAssetTask;
  96766. /**
  96767. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  96768. */
  96769. var TextureAssetTask = /** @class */ (function (_super) {
  96770. __extends(TextureAssetTask, _super);
  96771. /**
  96772. * Creates a new TextureAssetTask object
  96773. * @param name defines the name of the task
  96774. * @param url defines the location of the file to load
  96775. * @param noMipmap defines if mipmap should not be generated (default is false)
  96776. * @param invertY defines if texture must be inverted on Y axis (default is false)
  96777. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96778. */
  96779. function TextureAssetTask(
  96780. /**
  96781. * Defines the name of the task
  96782. */
  96783. name,
  96784. /**
  96785. * Defines the location of the file to load
  96786. */
  96787. url,
  96788. /**
  96789. * Defines if mipmap should not be generated (default is false)
  96790. */
  96791. noMipmap,
  96792. /**
  96793. * Defines if texture must be inverted on Y axis (default is false)
  96794. */
  96795. invertY,
  96796. /**
  96797. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  96798. */
  96799. samplingMode) {
  96800. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  96801. var _this = _super.call(this, name) || this;
  96802. _this.name = name;
  96803. _this.url = url;
  96804. _this.noMipmap = noMipmap;
  96805. _this.invertY = invertY;
  96806. _this.samplingMode = samplingMode;
  96807. return _this;
  96808. }
  96809. /**
  96810. * Execute the current task
  96811. * @param scene defines the scene where you want your assets to be loaded
  96812. * @param onSuccess is a callback called when the task is successfully executed
  96813. * @param onError is a callback called if an error occurs
  96814. */
  96815. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96816. var onload = function () {
  96817. onSuccess();
  96818. };
  96819. var onerror = function (message, exception) {
  96820. onError(message, exception);
  96821. };
  96822. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  96823. };
  96824. return TextureAssetTask;
  96825. }(AbstractAssetTask));
  96826. BABYLON.TextureAssetTask = TextureAssetTask;
  96827. /**
  96828. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  96829. */
  96830. var CubeTextureAssetTask = /** @class */ (function (_super) {
  96831. __extends(CubeTextureAssetTask, _super);
  96832. /**
  96833. * Creates a new CubeTextureAssetTask
  96834. * @param name defines the name of the task
  96835. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96836. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96837. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96838. * @param files defines the explicit list of files (undefined by default)
  96839. */
  96840. function CubeTextureAssetTask(
  96841. /**
  96842. * Defines the name of the task
  96843. */
  96844. name,
  96845. /**
  96846. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  96847. */
  96848. url,
  96849. /**
  96850. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  96851. */
  96852. extensions,
  96853. /**
  96854. * Defines if mipmaps should not be generated (default is false)
  96855. */
  96856. noMipmap,
  96857. /**
  96858. * Defines the explicit list of files (undefined by default)
  96859. */
  96860. files) {
  96861. var _this = _super.call(this, name) || this;
  96862. _this.name = name;
  96863. _this.url = url;
  96864. _this.extensions = extensions;
  96865. _this.noMipmap = noMipmap;
  96866. _this.files = files;
  96867. return _this;
  96868. }
  96869. /**
  96870. * Execute the current task
  96871. * @param scene defines the scene where you want your assets to be loaded
  96872. * @param onSuccess is a callback called when the task is successfully executed
  96873. * @param onError is a callback called if an error occurs
  96874. */
  96875. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  96876. var onload = function () {
  96877. onSuccess();
  96878. };
  96879. var onerror = function (message, exception) {
  96880. onError(message, exception);
  96881. };
  96882. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  96883. };
  96884. return CubeTextureAssetTask;
  96885. }(AbstractAssetTask));
  96886. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  96887. /**
  96888. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  96889. */
  96890. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  96891. __extends(HDRCubeTextureAssetTask, _super);
  96892. /**
  96893. * Creates a new HDRCubeTextureAssetTask object
  96894. * @param name defines the name of the task
  96895. * @param url defines the location of the file to load
  96896. * @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.
  96897. * @param noMipmap defines if mipmaps should not be generated (default is false)
  96898. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96899. * @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)
  96900. * @param reserved Internal use only
  96901. */
  96902. function HDRCubeTextureAssetTask(
  96903. /**
  96904. * Defines the name of the task
  96905. */
  96906. name,
  96907. /**
  96908. * Defines the location of the file to load
  96909. */
  96910. url,
  96911. /**
  96912. * Defines the desired size (the more it increases the longer the generation will be)
  96913. */
  96914. size,
  96915. /**
  96916. * Defines if mipmaps should not be generated (default is false)
  96917. */
  96918. noMipmap,
  96919. /**
  96920. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  96921. */
  96922. generateHarmonics,
  96923. /**
  96924. * 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)
  96925. */
  96926. gammaSpace,
  96927. /**
  96928. * Internal Use Only
  96929. */
  96930. reserved) {
  96931. if (noMipmap === void 0) { noMipmap = false; }
  96932. if (generateHarmonics === void 0) { generateHarmonics = true; }
  96933. if (gammaSpace === void 0) { gammaSpace = false; }
  96934. if (reserved === void 0) { reserved = false; }
  96935. var _this = _super.call(this, name) || this;
  96936. _this.name = name;
  96937. _this.url = url;
  96938. _this.size = size;
  96939. _this.noMipmap = noMipmap;
  96940. _this.generateHarmonics = generateHarmonics;
  96941. _this.gammaSpace = gammaSpace;
  96942. _this.reserved = reserved;
  96943. return _this;
  96944. }
  96945. /**
  96946. * Execute the current task
  96947. * @param scene defines the scene where you want your assets to be loaded
  96948. * @param onSuccess is a callback called when the task is successfully executed
  96949. * @param onError is a callback called if an error occurs
  96950. */
  96951. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  96952. var onload = function () {
  96953. onSuccess();
  96954. };
  96955. var onerror = function (message, exception) {
  96956. onError(message, exception);
  96957. };
  96958. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  96959. };
  96960. return HDRCubeTextureAssetTask;
  96961. }(AbstractAssetTask));
  96962. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  96963. /**
  96964. * This class can be used to easily import assets into a scene
  96965. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  96966. */
  96967. var AssetsManager = /** @class */ (function () {
  96968. /**
  96969. * Creates a new AssetsManager
  96970. * @param scene defines the scene to work on
  96971. */
  96972. function AssetsManager(scene) {
  96973. this._isLoading = false;
  96974. this._tasks = new Array();
  96975. this._waitingTasksCount = 0;
  96976. this._totalTasksCount = 0;
  96977. /**
  96978. * Observable called when all tasks are processed
  96979. */
  96980. this.onTaskSuccessObservable = new BABYLON.Observable();
  96981. /**
  96982. * Observable called when a task had an error
  96983. */
  96984. this.onTaskErrorObservable = new BABYLON.Observable();
  96985. /**
  96986. * Observable called when a task is successful
  96987. */
  96988. this.onTasksDoneObservable = new BABYLON.Observable();
  96989. /**
  96990. * Observable called when a task is done (whatever the result is)
  96991. */
  96992. this.onProgressObservable = new BABYLON.Observable();
  96993. /**
  96994. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  96995. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  96996. */
  96997. this.useDefaultLoadingScreen = true;
  96998. this._scene = scene;
  96999. }
  97000. /**
  97001. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97002. * @param taskName defines the name of the new task
  97003. * @param meshesNames defines the name of meshes to load
  97004. * @param rootUrl defines the root url to use to locate files
  97005. * @param sceneFilename defines the filename of the scene file
  97006. * @returns a new {BABYLON.MeshAssetTask} object
  97007. */
  97008. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97009. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97010. this._tasks.push(task);
  97011. return task;
  97012. };
  97013. /**
  97014. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97015. * @param taskName defines the name of the new task
  97016. * @param url defines the url of the file to load
  97017. * @returns a new {BABYLON.TextFileAssetTask} object
  97018. */
  97019. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97020. var task = new TextFileAssetTask(taskName, url);
  97021. this._tasks.push(task);
  97022. return task;
  97023. };
  97024. /**
  97025. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97026. * @param taskName defines the name of the new task
  97027. * @param url defines the url of the file to load
  97028. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97029. */
  97030. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97031. var task = new BinaryFileAssetTask(taskName, url);
  97032. this._tasks.push(task);
  97033. return task;
  97034. };
  97035. /**
  97036. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97037. * @param taskName defines the name of the new task
  97038. * @param url defines the url of the file to load
  97039. * @returns a new {BABYLON.ImageAssetTask} object
  97040. */
  97041. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97042. var task = new ImageAssetTask(taskName, url);
  97043. this._tasks.push(task);
  97044. return task;
  97045. };
  97046. /**
  97047. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97048. * @param taskName defines the name of the new task
  97049. * @param url defines the url of the file to load
  97050. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97051. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97052. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97053. * @returns a new {BABYLON.TextureAssetTask} object
  97054. */
  97055. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97056. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97057. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97058. this._tasks.push(task);
  97059. return task;
  97060. };
  97061. /**
  97062. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97063. * @param taskName defines the name of the new task
  97064. * @param url defines the url of the file to load
  97065. * @param extensions defines the extension to use to load the cube map (can be null)
  97066. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97067. * @param files defines the list of files to load (can be null)
  97068. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97069. */
  97070. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97071. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97072. this._tasks.push(task);
  97073. return task;
  97074. };
  97075. /**
  97076. *
  97077. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97078. * @param taskName defines the name of the new task
  97079. * @param url defines the url of the file to load
  97080. * @param size defines the size you want for the cubemap (can be null)
  97081. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97082. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97083. * @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)
  97084. * @param reserved Internal use only
  97085. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97086. */
  97087. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97088. if (noMipmap === void 0) { noMipmap = false; }
  97089. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97090. if (gammaSpace === void 0) { gammaSpace = false; }
  97091. if (reserved === void 0) { reserved = false; }
  97092. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97093. this._tasks.push(task);
  97094. return task;
  97095. };
  97096. /**
  97097. * Remove a task from the assets manager.
  97098. * @param task the task to remove
  97099. */
  97100. AssetsManager.prototype.removeTask = function (task) {
  97101. var index = this._tasks.indexOf(task);
  97102. if (index > -1) {
  97103. this._tasks.splice(index, 1);
  97104. }
  97105. };
  97106. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97107. this._waitingTasksCount--;
  97108. try {
  97109. if (this.onProgress) {
  97110. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97111. }
  97112. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97113. }
  97114. catch (e) {
  97115. BABYLON.Tools.Error("Error running progress callbacks.");
  97116. console.log(e);
  97117. }
  97118. if (this._waitingTasksCount === 0) {
  97119. try {
  97120. if (this.onFinish) {
  97121. this.onFinish(this._tasks);
  97122. }
  97123. // Let's remove successfull tasks
  97124. var currentTasks = this._tasks.slice();
  97125. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97126. var task = currentTasks_1[_i];
  97127. if (task.taskState === AssetTaskState.DONE) {
  97128. var index = this._tasks.indexOf(task);
  97129. if (index > -1) {
  97130. this._tasks.splice(index, 1);
  97131. }
  97132. }
  97133. }
  97134. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97135. }
  97136. catch (e) {
  97137. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97138. console.log(e);
  97139. }
  97140. this._isLoading = false;
  97141. this._scene.getEngine().hideLoadingUI();
  97142. }
  97143. };
  97144. AssetsManager.prototype._runTask = function (task) {
  97145. var _this = this;
  97146. var done = function () {
  97147. try {
  97148. if (_this.onTaskSuccess) {
  97149. _this.onTaskSuccess(task);
  97150. }
  97151. _this.onTaskSuccessObservable.notifyObservers(task);
  97152. _this._decreaseWaitingTasksCount(task);
  97153. }
  97154. catch (e) {
  97155. error("Error executing task success callbacks", e);
  97156. }
  97157. };
  97158. var error = function (message, exception) {
  97159. task._setErrorObject(message, exception);
  97160. if (_this.onTaskError) {
  97161. _this.onTaskError(task);
  97162. }
  97163. _this.onTaskErrorObservable.notifyObservers(task);
  97164. _this._decreaseWaitingTasksCount(task);
  97165. };
  97166. task.run(this._scene, done, error);
  97167. };
  97168. /**
  97169. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97170. * @return the current instance of the {BABYLON.AssetsManager}
  97171. */
  97172. AssetsManager.prototype.reset = function () {
  97173. this._isLoading = false;
  97174. this._tasks = new Array();
  97175. return this;
  97176. };
  97177. /**
  97178. * Start the loading process
  97179. * @return the current instance of the {BABYLON.AssetsManager}
  97180. */
  97181. AssetsManager.prototype.load = function () {
  97182. if (this._isLoading) {
  97183. return this;
  97184. }
  97185. this._isLoading = true;
  97186. this._waitingTasksCount = this._tasks.length;
  97187. this._totalTasksCount = this._tasks.length;
  97188. if (this._waitingTasksCount === 0) {
  97189. this._isLoading = false;
  97190. if (this.onFinish) {
  97191. this.onFinish(this._tasks);
  97192. }
  97193. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97194. return this;
  97195. }
  97196. if (this.useDefaultLoadingScreen) {
  97197. this._scene.getEngine().displayLoadingUI();
  97198. }
  97199. for (var index = 0; index < this._tasks.length; index++) {
  97200. var task = this._tasks[index];
  97201. if (task.taskState === AssetTaskState.INIT) {
  97202. this._runTask(task);
  97203. }
  97204. }
  97205. return this;
  97206. };
  97207. return AssetsManager;
  97208. }());
  97209. BABYLON.AssetsManager = AssetsManager;
  97210. })(BABYLON || (BABYLON = {}));
  97211. //# sourceMappingURL=babylon.assetsManager.js.map
  97212. var BABYLON;
  97213. (function (BABYLON) {
  97214. var serializedGeometries = [];
  97215. var serializeGeometry = function (geometry, serializationGeometries) {
  97216. if (serializedGeometries[geometry.id]) {
  97217. return;
  97218. }
  97219. if (geometry.doNotSerialize) {
  97220. return;
  97221. }
  97222. if (geometry instanceof BABYLON.BoxGeometry) {
  97223. serializationGeometries.boxes.push(geometry.serialize());
  97224. }
  97225. else if (geometry instanceof BABYLON.SphereGeometry) {
  97226. serializationGeometries.spheres.push(geometry.serialize());
  97227. }
  97228. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97229. serializationGeometries.cylinders.push(geometry.serialize());
  97230. }
  97231. else if (geometry instanceof BABYLON.TorusGeometry) {
  97232. serializationGeometries.toruses.push(geometry.serialize());
  97233. }
  97234. else if (geometry instanceof BABYLON.GroundGeometry) {
  97235. serializationGeometries.grounds.push(geometry.serialize());
  97236. }
  97237. else if (geometry instanceof BABYLON.Plane) {
  97238. serializationGeometries.planes.push(geometry.serialize());
  97239. }
  97240. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97241. serializationGeometries.torusKnots.push(geometry.serialize());
  97242. }
  97243. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97244. throw new Error("Unknown primitive type");
  97245. }
  97246. else {
  97247. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97248. }
  97249. serializedGeometries[geometry.id] = true;
  97250. };
  97251. var serializeMesh = function (mesh, serializationScene) {
  97252. var serializationObject = {};
  97253. // Geometry
  97254. var geometry = mesh._geometry;
  97255. if (geometry) {
  97256. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97257. // 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
  97258. serializeGeometry(geometry, serializationScene.geometries);
  97259. }
  97260. }
  97261. // Custom
  97262. if (mesh.serialize) {
  97263. mesh.serialize(serializationObject);
  97264. }
  97265. return serializationObject;
  97266. };
  97267. var finalizeSingleMesh = function (mesh, serializationObject) {
  97268. //only works if the mesh is already loaded
  97269. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97270. //serialize material
  97271. if (mesh.material) {
  97272. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97273. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97274. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97275. serializationObject.multiMaterials.push(mesh.material.serialize());
  97276. }
  97277. }
  97278. else {
  97279. serializationObject.materials = serializationObject.materials || [];
  97280. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97281. serializationObject.materials.push(mesh.material.serialize());
  97282. }
  97283. }
  97284. }
  97285. //serialize geometry
  97286. var geometry = mesh._geometry;
  97287. if (geometry) {
  97288. if (!serializationObject.geometries) {
  97289. serializationObject.geometries = {};
  97290. serializationObject.geometries.boxes = [];
  97291. serializationObject.geometries.spheres = [];
  97292. serializationObject.geometries.cylinders = [];
  97293. serializationObject.geometries.toruses = [];
  97294. serializationObject.geometries.grounds = [];
  97295. serializationObject.geometries.planes = [];
  97296. serializationObject.geometries.torusKnots = [];
  97297. serializationObject.geometries.vertexData = [];
  97298. }
  97299. serializeGeometry(geometry, serializationObject.geometries);
  97300. }
  97301. // Skeletons
  97302. if (mesh.skeleton) {
  97303. serializationObject.skeletons = serializationObject.skeletons || [];
  97304. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97305. }
  97306. //serialize the actual mesh
  97307. serializationObject.meshes = serializationObject.meshes || [];
  97308. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97309. }
  97310. };
  97311. var SceneSerializer = /** @class */ (function () {
  97312. function SceneSerializer() {
  97313. }
  97314. SceneSerializer.ClearCache = function () {
  97315. serializedGeometries = [];
  97316. };
  97317. SceneSerializer.Serialize = function (scene) {
  97318. var serializationObject = {};
  97319. SceneSerializer.ClearCache();
  97320. // Scene
  97321. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97322. serializationObject.autoClear = scene.autoClear;
  97323. serializationObject.clearColor = scene.clearColor.asArray();
  97324. serializationObject.ambientColor = scene.ambientColor.asArray();
  97325. serializationObject.gravity = scene.gravity.asArray();
  97326. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97327. serializationObject.workerCollisions = scene.workerCollisions;
  97328. // Fog
  97329. if (scene.fogMode && scene.fogMode !== 0) {
  97330. serializationObject.fogMode = scene.fogMode;
  97331. serializationObject.fogColor = scene.fogColor.asArray();
  97332. serializationObject.fogStart = scene.fogStart;
  97333. serializationObject.fogEnd = scene.fogEnd;
  97334. serializationObject.fogDensity = scene.fogDensity;
  97335. }
  97336. //Physics
  97337. if (scene.isPhysicsEnabled()) {
  97338. var physicEngine = scene.getPhysicsEngine();
  97339. if (physicEngine) {
  97340. serializationObject.physicsEnabled = true;
  97341. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97342. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97343. }
  97344. }
  97345. // Metadata
  97346. if (scene.metadata) {
  97347. serializationObject.metadata = scene.metadata;
  97348. }
  97349. // Morph targets
  97350. serializationObject.morphTargetManagers = [];
  97351. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97352. var abstractMesh = _a[_i];
  97353. var manager = abstractMesh.morphTargetManager;
  97354. if (manager) {
  97355. serializationObject.morphTargetManagers.push(manager.serialize());
  97356. }
  97357. }
  97358. // Lights
  97359. serializationObject.lights = [];
  97360. var index;
  97361. var light;
  97362. for (index = 0; index < scene.lights.length; index++) {
  97363. light = scene.lights[index];
  97364. if (!light.doNotSerialize) {
  97365. serializationObject.lights.push(light.serialize());
  97366. }
  97367. }
  97368. // Cameras
  97369. serializationObject.cameras = [];
  97370. for (index = 0; index < scene.cameras.length; index++) {
  97371. var camera = scene.cameras[index];
  97372. if (!camera.doNotSerialize) {
  97373. serializationObject.cameras.push(camera.serialize());
  97374. }
  97375. }
  97376. if (scene.activeCamera) {
  97377. serializationObject.activeCameraID = scene.activeCamera.id;
  97378. }
  97379. // Animations
  97380. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97381. // Materials
  97382. serializationObject.materials = [];
  97383. serializationObject.multiMaterials = [];
  97384. var material;
  97385. for (index = 0; index < scene.materials.length; index++) {
  97386. material = scene.materials[index];
  97387. if (!material.doNotSerialize) {
  97388. serializationObject.materials.push(material.serialize());
  97389. }
  97390. }
  97391. // MultiMaterials
  97392. serializationObject.multiMaterials = [];
  97393. for (index = 0; index < scene.multiMaterials.length; index++) {
  97394. var multiMaterial = scene.multiMaterials[index];
  97395. serializationObject.multiMaterials.push(multiMaterial.serialize());
  97396. }
  97397. // Environment texture
  97398. if (scene.environmentTexture) {
  97399. serializationObject.environmentTexture = scene.environmentTexture.name;
  97400. }
  97401. // Skeletons
  97402. serializationObject.skeletons = [];
  97403. for (index = 0; index < scene.skeletons.length; index++) {
  97404. var skeleton = scene.skeletons[index];
  97405. if (!skeleton.doNotSerialize) {
  97406. serializationObject.skeletons.push(skeleton.serialize());
  97407. }
  97408. }
  97409. // Transform nodes
  97410. serializationObject.transformNodes = [];
  97411. for (index = 0; index < scene.transformNodes.length; index++) {
  97412. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  97413. }
  97414. // Geometries
  97415. serializationObject.geometries = {};
  97416. serializationObject.geometries.boxes = [];
  97417. serializationObject.geometries.spheres = [];
  97418. serializationObject.geometries.cylinders = [];
  97419. serializationObject.geometries.toruses = [];
  97420. serializationObject.geometries.grounds = [];
  97421. serializationObject.geometries.planes = [];
  97422. serializationObject.geometries.torusKnots = [];
  97423. serializationObject.geometries.vertexData = [];
  97424. serializedGeometries = [];
  97425. var geometries = scene.getGeometries();
  97426. for (index = 0; index < geometries.length; index++) {
  97427. var geometry = geometries[index];
  97428. if (geometry.isReady()) {
  97429. serializeGeometry(geometry, serializationObject.geometries);
  97430. }
  97431. }
  97432. // Meshes
  97433. serializationObject.meshes = [];
  97434. for (index = 0; index < scene.meshes.length; index++) {
  97435. var abstractMesh = scene.meshes[index];
  97436. if (abstractMesh instanceof BABYLON.Mesh) {
  97437. var mesh = abstractMesh;
  97438. if (!mesh.doNotSerialize) {
  97439. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97440. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97441. }
  97442. }
  97443. }
  97444. }
  97445. // Particles Systems
  97446. serializationObject.particleSystems = [];
  97447. for (index = 0; index < scene.particleSystems.length; index++) {
  97448. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  97449. }
  97450. // Lens flares
  97451. serializationObject.lensFlareSystems = [];
  97452. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  97453. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  97454. }
  97455. // Shadows
  97456. serializationObject.shadowGenerators = [];
  97457. for (index = 0; index < scene.lights.length; index++) {
  97458. light = scene.lights[index];
  97459. var shadowGenerator = light.getShadowGenerator();
  97460. if (shadowGenerator) {
  97461. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  97462. }
  97463. }
  97464. // Action Manager
  97465. if (scene.actionManager) {
  97466. serializationObject.actions = scene.actionManager.serialize("scene");
  97467. }
  97468. // Audio
  97469. serializationObject.sounds = [];
  97470. for (index = 0; index < scene.soundTracks.length; index++) {
  97471. var soundtrack = scene.soundTracks[index];
  97472. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  97473. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  97474. }
  97475. }
  97476. // Effect layers
  97477. serializationObject.effectLayers = [];
  97478. for (index = 0; index < scene.effectLayers.length; index++) {
  97479. var layer = scene.effectLayers[index];
  97480. if (layer.serialize) {
  97481. serializationObject.effectLayers.push(layer.serialize());
  97482. }
  97483. }
  97484. return serializationObject;
  97485. };
  97486. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  97487. if (withParents === void 0) { withParents = false; }
  97488. if (withChildren === void 0) { withChildren = false; }
  97489. var serializationObject = {};
  97490. SceneSerializer.ClearCache();
  97491. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  97492. if (withParents || withChildren) {
  97493. //deliberate for loop! not for each, appended should be processed as well.
  97494. for (var i = 0; i < toSerialize.length; ++i) {
  97495. if (withChildren) {
  97496. toSerialize[i].getDescendants().forEach(function (node) {
  97497. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  97498. toSerialize.push(node);
  97499. }
  97500. });
  97501. }
  97502. //make sure the array doesn't contain the object already
  97503. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  97504. toSerialize.push(toSerialize[i].parent);
  97505. }
  97506. }
  97507. }
  97508. toSerialize.forEach(function (mesh) {
  97509. finalizeSingleMesh(mesh, serializationObject);
  97510. });
  97511. return serializationObject;
  97512. };
  97513. return SceneSerializer;
  97514. }());
  97515. BABYLON.SceneSerializer = SceneSerializer;
  97516. })(BABYLON || (BABYLON = {}));
  97517. //# sourceMappingURL=babylon.sceneSerializer.js.map
  97518. var BABYLON;
  97519. (function (BABYLON) {
  97520. var ReflectionProbe = /** @class */ (function () {
  97521. function ReflectionProbe(name, size, scene, generateMipMaps) {
  97522. if (generateMipMaps === void 0) { generateMipMaps = true; }
  97523. var _this = this;
  97524. this.name = name;
  97525. this._viewMatrix = BABYLON.Matrix.Identity();
  97526. this._target = BABYLON.Vector3.Zero();
  97527. this._add = BABYLON.Vector3.Zero();
  97528. this._invertYAxis = false;
  97529. this.position = BABYLON.Vector3.Zero();
  97530. this._scene = scene;
  97531. this._scene.reflectionProbes.push(this);
  97532. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  97533. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  97534. switch (faceIndex) {
  97535. case 0:
  97536. _this._add.copyFromFloats(1, 0, 0);
  97537. break;
  97538. case 1:
  97539. _this._add.copyFromFloats(-1, 0, 0);
  97540. break;
  97541. case 2:
  97542. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  97543. break;
  97544. case 3:
  97545. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  97546. break;
  97547. case 4:
  97548. _this._add.copyFromFloats(0, 0, 1);
  97549. break;
  97550. case 5:
  97551. _this._add.copyFromFloats(0, 0, -1);
  97552. break;
  97553. }
  97554. if (_this._attachedMesh) {
  97555. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  97556. }
  97557. _this.position.addToRef(_this._add, _this._target);
  97558. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  97559. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  97560. scene._forcedViewPosition = _this.position;
  97561. });
  97562. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  97563. scene._forcedViewPosition = null;
  97564. scene.updateTransformMatrix(true);
  97565. });
  97566. if (scene.activeCamera) {
  97567. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  97568. }
  97569. }
  97570. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  97571. get: function () {
  97572. return this._renderTargetTexture.samples;
  97573. },
  97574. set: function (value) {
  97575. this._renderTargetTexture.samples = value;
  97576. },
  97577. enumerable: true,
  97578. configurable: true
  97579. });
  97580. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  97581. get: function () {
  97582. return this._renderTargetTexture.refreshRate;
  97583. },
  97584. set: function (value) {
  97585. this._renderTargetTexture.refreshRate = value;
  97586. },
  97587. enumerable: true,
  97588. configurable: true
  97589. });
  97590. ReflectionProbe.prototype.getScene = function () {
  97591. return this._scene;
  97592. };
  97593. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  97594. get: function () {
  97595. return this._renderTargetTexture;
  97596. },
  97597. enumerable: true,
  97598. configurable: true
  97599. });
  97600. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  97601. get: function () {
  97602. return this._renderTargetTexture.renderList;
  97603. },
  97604. enumerable: true,
  97605. configurable: true
  97606. });
  97607. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  97608. this._attachedMesh = mesh;
  97609. };
  97610. /**
  97611. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  97612. *
  97613. * @param renderingGroupId The rendering group id corresponding to its index
  97614. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  97615. */
  97616. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  97617. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  97618. };
  97619. ReflectionProbe.prototype.dispose = function () {
  97620. var index = this._scene.reflectionProbes.indexOf(this);
  97621. if (index !== -1) {
  97622. // Remove from the scene if found
  97623. this._scene.reflectionProbes.splice(index, 1);
  97624. }
  97625. if (this._renderTargetTexture) {
  97626. this._renderTargetTexture.dispose();
  97627. this._renderTargetTexture = null;
  97628. }
  97629. };
  97630. return ReflectionProbe;
  97631. }());
  97632. BABYLON.ReflectionProbe = ReflectionProbe;
  97633. })(BABYLON || (BABYLON = {}));
  97634. //# sourceMappingURL=babylon.reflectionProbe.js.map
  97635. var BABYLON;
  97636. (function (BABYLON) {
  97637. var Layer = /** @class */ (function () {
  97638. function Layer(name, imgUrl, scene, isBackground, color) {
  97639. this.name = name;
  97640. this.scale = new BABYLON.Vector2(1, 1);
  97641. this.offset = new BABYLON.Vector2(0, 0);
  97642. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  97643. this.layerMask = 0x0FFFFFFF;
  97644. this._vertexBuffers = {};
  97645. // Events
  97646. /**
  97647. * An event triggered when the layer is disposed.
  97648. */
  97649. this.onDisposeObservable = new BABYLON.Observable();
  97650. /**
  97651. * An event triggered before rendering the scene
  97652. */
  97653. this.onBeforeRenderObservable = new BABYLON.Observable();
  97654. /**
  97655. * An event triggered after rendering the scene
  97656. */
  97657. this.onAfterRenderObservable = new BABYLON.Observable();
  97658. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  97659. this.isBackground = isBackground === undefined ? true : isBackground;
  97660. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  97661. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  97662. this._scene.layers.push(this);
  97663. var engine = this._scene.getEngine();
  97664. // VBO
  97665. var vertices = [];
  97666. vertices.push(1, 1);
  97667. vertices.push(-1, 1);
  97668. vertices.push(-1, -1);
  97669. vertices.push(1, -1);
  97670. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  97671. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  97672. this._createIndexBuffer();
  97673. // Effects
  97674. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  97675. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  97676. }
  97677. Object.defineProperty(Layer.prototype, "onDispose", {
  97678. set: function (callback) {
  97679. if (this._onDisposeObserver) {
  97680. this.onDisposeObservable.remove(this._onDisposeObserver);
  97681. }
  97682. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  97683. },
  97684. enumerable: true,
  97685. configurable: true
  97686. });
  97687. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  97688. set: function (callback) {
  97689. if (this._onBeforeRenderObserver) {
  97690. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  97691. }
  97692. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  97693. },
  97694. enumerable: true,
  97695. configurable: true
  97696. });
  97697. Object.defineProperty(Layer.prototype, "onAfterRender", {
  97698. set: function (callback) {
  97699. if (this._onAfterRenderObserver) {
  97700. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  97701. }
  97702. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  97703. },
  97704. enumerable: true,
  97705. configurable: true
  97706. });
  97707. Layer.prototype._createIndexBuffer = function () {
  97708. var engine = this._scene.getEngine();
  97709. // Indices
  97710. var indices = [];
  97711. indices.push(0);
  97712. indices.push(1);
  97713. indices.push(2);
  97714. indices.push(0);
  97715. indices.push(2);
  97716. indices.push(3);
  97717. this._indexBuffer = engine.createIndexBuffer(indices);
  97718. };
  97719. Layer.prototype._rebuild = function () {
  97720. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97721. if (vb) {
  97722. vb._rebuild();
  97723. }
  97724. this._createIndexBuffer();
  97725. };
  97726. Layer.prototype.render = function () {
  97727. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  97728. // Check
  97729. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  97730. return;
  97731. var engine = this._scene.getEngine();
  97732. this.onBeforeRenderObservable.notifyObservers(this);
  97733. // Render
  97734. engine.enableEffect(currentEffect);
  97735. engine.setState(false);
  97736. // Texture
  97737. currentEffect.setTexture("textureSampler", this.texture);
  97738. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  97739. // Color
  97740. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  97741. // Scale / offset
  97742. currentEffect.setVector2("offset", this.offset);
  97743. currentEffect.setVector2("scale", this.scale);
  97744. // VBOs
  97745. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  97746. // Draw order
  97747. if (!this.alphaTest) {
  97748. engine.setAlphaMode(this.alphaBlendingMode);
  97749. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97750. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  97751. }
  97752. else {
  97753. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97754. }
  97755. this.onAfterRenderObservable.notifyObservers(this);
  97756. };
  97757. Layer.prototype.dispose = function () {
  97758. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  97759. if (vertexBuffer) {
  97760. vertexBuffer.dispose();
  97761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  97762. }
  97763. if (this._indexBuffer) {
  97764. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  97765. this._indexBuffer = null;
  97766. }
  97767. if (this.texture) {
  97768. this.texture.dispose();
  97769. this.texture = null;
  97770. }
  97771. // Remove from scene
  97772. var index = this._scene.layers.indexOf(this);
  97773. this._scene.layers.splice(index, 1);
  97774. // Callback
  97775. this.onDisposeObservable.notifyObservers(this);
  97776. this.onDisposeObservable.clear();
  97777. this.onAfterRenderObservable.clear();
  97778. this.onBeforeRenderObservable.clear();
  97779. };
  97780. return Layer;
  97781. }());
  97782. BABYLON.Layer = Layer;
  97783. })(BABYLON || (BABYLON = {}));
  97784. //# sourceMappingURL=babylon.layer.js.map
  97785. var BABYLON;
  97786. (function (BABYLON) {
  97787. var TextureTools = /** @class */ (function () {
  97788. function TextureTools() {
  97789. }
  97790. /**
  97791. * Uses the GPU to create a copy texture rescaled at a given size
  97792. * @param texture Texture to copy from
  97793. * @param width Desired width
  97794. * @param height Desired height
  97795. * @return Generated texture
  97796. */
  97797. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  97798. if (useBilinearMode === void 0) { useBilinearMode = true; }
  97799. var scene = texture.getScene();
  97800. var engine = scene.getEngine();
  97801. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  97802. rtt.wrapU = texture.wrapU;
  97803. rtt.wrapV = texture.wrapV;
  97804. rtt.uOffset = texture.uOffset;
  97805. rtt.vOffset = texture.vOffset;
  97806. rtt.uScale = texture.uScale;
  97807. rtt.vScale = texture.vScale;
  97808. rtt.uAng = texture.uAng;
  97809. rtt.vAng = texture.vAng;
  97810. rtt.wAng = texture.wAng;
  97811. rtt.coordinatesIndex = texture.coordinatesIndex;
  97812. rtt.level = texture.level;
  97813. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  97814. rtt._texture.isReady = false;
  97815. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97816. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97817. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  97818. passPostProcess.getEffect().executeWhenCompiled(function () {
  97819. passPostProcess.onApply = function (effect) {
  97820. effect.setTexture("textureSampler", texture);
  97821. };
  97822. var internalTexture = rtt.getInternalTexture();
  97823. if (internalTexture) {
  97824. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  97825. engine.unBindFramebuffer(internalTexture);
  97826. rtt.disposeFramebufferObjects();
  97827. passPostProcess.dispose();
  97828. internalTexture.isReady = true;
  97829. }
  97830. });
  97831. return rtt;
  97832. };
  97833. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  97834. if (!scene._environmentBRDFTexture) {
  97835. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  97836. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97837. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97838. scene._environmentBRDFTexture = texture;
  97839. }
  97840. return scene._environmentBRDFTexture;
  97841. };
  97842. 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=";
  97843. return TextureTools;
  97844. }());
  97845. BABYLON.TextureTools = TextureTools;
  97846. })(BABYLON || (BABYLON = {}));
  97847. //# sourceMappingURL=babylon.textureTools.js.map
  97848. var BABYLON;
  97849. (function (BABYLON) {
  97850. var FramingBehavior = /** @class */ (function () {
  97851. function FramingBehavior() {
  97852. this._mode = FramingBehavior.FitFrustumSidesMode;
  97853. this._radiusScale = 1.0;
  97854. this._positionScale = 0.5;
  97855. this._defaultElevation = 0.3;
  97856. this._elevationReturnTime = 1500;
  97857. this._elevationReturnWaitTime = 1000;
  97858. this._zoomStopsAnimation = false;
  97859. this._framingTime = 1500;
  97860. this._isPointerDown = false;
  97861. this._lastInteractionTime = -Infinity;
  97862. // Framing control
  97863. this._animatables = new Array();
  97864. this._betaIsAnimating = false;
  97865. }
  97866. Object.defineProperty(FramingBehavior.prototype, "name", {
  97867. get: function () {
  97868. return "Framing";
  97869. },
  97870. enumerable: true,
  97871. configurable: true
  97872. });
  97873. Object.defineProperty(FramingBehavior.prototype, "mode", {
  97874. /**
  97875. * Gets current mode used by the behavior.
  97876. */
  97877. get: function () {
  97878. return this._mode;
  97879. },
  97880. /**
  97881. * Sets the current mode used by the behavior
  97882. */
  97883. set: function (mode) {
  97884. this._mode = mode;
  97885. },
  97886. enumerable: true,
  97887. configurable: true
  97888. });
  97889. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  97890. /**
  97891. * Gets the scale applied to the radius
  97892. */
  97893. get: function () {
  97894. return this._radiusScale;
  97895. },
  97896. /**
  97897. * Sets the scale applied to the radius (1 by default)
  97898. */
  97899. set: function (radius) {
  97900. this._radiusScale = radius;
  97901. },
  97902. enumerable: true,
  97903. configurable: true
  97904. });
  97905. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  97906. /**
  97907. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97908. */
  97909. get: function () {
  97910. return this._positionScale;
  97911. },
  97912. /**
  97913. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  97914. */
  97915. set: function (scale) {
  97916. this._positionScale = scale;
  97917. },
  97918. enumerable: true,
  97919. configurable: true
  97920. });
  97921. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  97922. /**
  97923. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97924. * behaviour is triggered, in radians.
  97925. */
  97926. get: function () {
  97927. return this._defaultElevation;
  97928. },
  97929. /**
  97930. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  97931. * behaviour is triggered, in radians.
  97932. */
  97933. set: function (elevation) {
  97934. this._defaultElevation = elevation;
  97935. },
  97936. enumerable: true,
  97937. configurable: true
  97938. });
  97939. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  97940. /**
  97941. * Gets the time (in milliseconds) taken to return to the default beta position.
  97942. * Negative value indicates camera should not return to default.
  97943. */
  97944. get: function () {
  97945. return this._elevationReturnTime;
  97946. },
  97947. /**
  97948. * Sets the time (in milliseconds) taken to return to the default beta position.
  97949. * Negative value indicates camera should not return to default.
  97950. */
  97951. set: function (speed) {
  97952. this._elevationReturnTime = speed;
  97953. },
  97954. enumerable: true,
  97955. configurable: true
  97956. });
  97957. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  97958. /**
  97959. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97960. */
  97961. get: function () {
  97962. return this._elevationReturnWaitTime;
  97963. },
  97964. /**
  97965. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  97966. */
  97967. set: function (time) {
  97968. this._elevationReturnWaitTime = time;
  97969. },
  97970. enumerable: true,
  97971. configurable: true
  97972. });
  97973. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  97974. /**
  97975. * Gets the flag that indicates if user zooming should stop animation.
  97976. */
  97977. get: function () {
  97978. return this._zoomStopsAnimation;
  97979. },
  97980. /**
  97981. * Sets the flag that indicates if user zooming should stop animation.
  97982. */
  97983. set: function (flag) {
  97984. this._zoomStopsAnimation = flag;
  97985. },
  97986. enumerable: true,
  97987. configurable: true
  97988. });
  97989. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  97990. /**
  97991. * Gets the transition time when framing the mesh, in milliseconds
  97992. */
  97993. get: function () {
  97994. return this._framingTime;
  97995. },
  97996. /**
  97997. * Sets the transition time when framing the mesh, in milliseconds
  97998. */
  97999. set: function (time) {
  98000. this._framingTime = time;
  98001. },
  98002. enumerable: true,
  98003. configurable: true
  98004. });
  98005. FramingBehavior.prototype.init = function () {
  98006. // Do notihng
  98007. };
  98008. FramingBehavior.prototype.attach = function (camera) {
  98009. var _this = this;
  98010. this._attachedCamera = camera;
  98011. var scene = this._attachedCamera.getScene();
  98012. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98013. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98014. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98015. _this._isPointerDown = true;
  98016. return;
  98017. }
  98018. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98019. _this._isPointerDown = false;
  98020. }
  98021. });
  98022. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98023. if (mesh) {
  98024. _this.zoomOnMesh(mesh);
  98025. }
  98026. });
  98027. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98028. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98029. _this._applyUserInteraction();
  98030. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98031. // back to the default position after a given timeout
  98032. _this._maintainCameraAboveGround();
  98033. });
  98034. };
  98035. FramingBehavior.prototype.detach = function () {
  98036. if (!this._attachedCamera) {
  98037. return;
  98038. }
  98039. var scene = this._attachedCamera.getScene();
  98040. if (this._onPrePointerObservableObserver) {
  98041. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98042. }
  98043. if (this._onAfterCheckInputsObserver) {
  98044. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98045. }
  98046. if (this._onMeshTargetChangedObserver) {
  98047. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98048. }
  98049. this._attachedCamera = null;
  98050. };
  98051. /**
  98052. * Targets the given mesh and updates zoom level accordingly.
  98053. * @param mesh The mesh to target.
  98054. * @param radius Optional. If a cached radius position already exists, overrides default.
  98055. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98056. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98057. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98058. */
  98059. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98060. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98061. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98062. mesh.computeWorldMatrix(true);
  98063. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98064. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98065. };
  98066. /**
  98067. * Targets the given mesh with its children and updates zoom level accordingly.
  98068. * @param mesh The mesh to target.
  98069. * @param radius Optional. If a cached radius position already exists, overrides default.
  98070. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98071. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98072. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98073. */
  98074. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98075. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98076. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98077. mesh.computeWorldMatrix(true);
  98078. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98079. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98080. };
  98081. /**
  98082. * Targets the given meshes with their children and updates zoom level accordingly.
  98083. * @param meshes The mesh to target.
  98084. * @param radius Optional. If a cached radius position already exists, overrides default.
  98085. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98086. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98087. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98088. */
  98089. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98090. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98091. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98092. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98093. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98094. for (var i = 0; i < meshes.length; i++) {
  98095. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98096. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98097. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98098. }
  98099. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98100. };
  98101. /**
  98102. * Targets the given mesh and updates zoom level accordingly.
  98103. * @param mesh The mesh to target.
  98104. * @param radius Optional. If a cached radius position already exists, overrides default.
  98105. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98106. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98107. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98108. */
  98109. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98110. var _this = this;
  98111. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98112. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98113. var zoomTarget;
  98114. if (!this._attachedCamera) {
  98115. return;
  98116. }
  98117. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98118. var bottom = minimumWorld.y;
  98119. var top = maximumWorld.y;
  98120. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98121. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98122. if (focusOnOriginXZ) {
  98123. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98124. }
  98125. else {
  98126. var centerWorld = minimumWorld.add(radiusWorld);
  98127. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98128. }
  98129. if (!this._vectorTransition) {
  98130. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98131. }
  98132. this._betaIsAnimating = true;
  98133. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98134. if (animatable) {
  98135. this._animatables.push(animatable);
  98136. }
  98137. // sets the radius and lower radius bounds
  98138. // Small delta ensures camera is not always at lower zoom limit.
  98139. var radius = 0;
  98140. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98141. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98142. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98143. radius = position;
  98144. }
  98145. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98146. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98147. if (this._attachedCamera.lowerRadiusLimit === null) {
  98148. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98149. }
  98150. }
  98151. // Set sensibilities
  98152. var extend = maximumWorld.subtract(minimumWorld).length();
  98153. this._attachedCamera.panningSensibility = 5000 / extend;
  98154. this._attachedCamera.wheelPrecision = 100 / radius;
  98155. // transition to new radius
  98156. if (!this._radiusTransition) {
  98157. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98158. }
  98159. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98160. _this.stopAllAnimations();
  98161. if (onAnimationEnd) {
  98162. onAnimationEnd();
  98163. }
  98164. if (_this._attachedCamera) {
  98165. _this._attachedCamera.storeState();
  98166. }
  98167. });
  98168. if (animatable) {
  98169. this._animatables.push(animatable);
  98170. }
  98171. };
  98172. /**
  98173. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98174. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98175. * frustum width.
  98176. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98177. * to fully enclose the mesh in the viewing frustum.
  98178. */
  98179. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98180. var size = maximumWorld.subtract(minimumWorld);
  98181. var boxVectorGlobalDiagonal = size.length();
  98182. var frustumSlope = this._getFrustumSlope();
  98183. // Formula for setting distance
  98184. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98185. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98186. // Horizon distance
  98187. var radius = radiusWithoutFraming * this._radiusScale;
  98188. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98189. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98190. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98191. var camera = this._attachedCamera;
  98192. if (!camera) {
  98193. return 0;
  98194. }
  98195. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98196. // Don't exceed the requested limit
  98197. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98198. }
  98199. // Don't exceed the upper radius limit
  98200. if (camera.upperRadiusLimit) {
  98201. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98202. }
  98203. return distance;
  98204. };
  98205. /**
  98206. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98207. * is automatically returned to its default position (expected to be above ground plane).
  98208. */
  98209. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98210. var _this = this;
  98211. if (this._elevationReturnTime < 0) {
  98212. return;
  98213. }
  98214. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98215. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98216. var limitBeta = Math.PI * 0.5;
  98217. // Bring the camera back up if below the ground plane
  98218. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98219. this._betaIsAnimating = true;
  98220. //Transition to new position
  98221. this.stopAllAnimations();
  98222. if (!this._betaTransition) {
  98223. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98224. }
  98225. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98226. _this._clearAnimationLocks();
  98227. _this.stopAllAnimations();
  98228. });
  98229. if (animatabe) {
  98230. this._animatables.push(animatabe);
  98231. }
  98232. }
  98233. };
  98234. /**
  98235. * Returns the frustum slope based on the canvas ratio and camera FOV
  98236. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98237. */
  98238. FramingBehavior.prototype._getFrustumSlope = function () {
  98239. // Calculate the viewport ratio
  98240. // Aspect Ratio is Height/Width.
  98241. var camera = this._attachedCamera;
  98242. if (!camera) {
  98243. return BABYLON.Vector2.Zero();
  98244. }
  98245. var engine = camera.getScene().getEngine();
  98246. var aspectRatio = engine.getAspectRatio(camera);
  98247. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98248. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98249. var frustumSlopeY = Math.tan(camera.fov / 2);
  98250. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98251. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98252. // along the forward vector.
  98253. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98254. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98255. };
  98256. /**
  98257. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98258. */
  98259. FramingBehavior.prototype._clearAnimationLocks = function () {
  98260. this._betaIsAnimating = false;
  98261. };
  98262. /**
  98263. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98264. */
  98265. FramingBehavior.prototype._applyUserInteraction = function () {
  98266. if (this.isUserIsMoving) {
  98267. this._lastInteractionTime = BABYLON.Tools.Now;
  98268. this.stopAllAnimations();
  98269. this._clearAnimationLocks();
  98270. }
  98271. };
  98272. /**
  98273. * Stops and removes all animations that have been applied to the camera
  98274. */
  98275. FramingBehavior.prototype.stopAllAnimations = function () {
  98276. if (this._attachedCamera) {
  98277. this._attachedCamera.animations = [];
  98278. }
  98279. while (this._animatables.length) {
  98280. if (this._animatables[0]) {
  98281. this._animatables[0].onAnimationEnd = null;
  98282. this._animatables[0].stop();
  98283. }
  98284. this._animatables.shift();
  98285. }
  98286. };
  98287. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98288. /**
  98289. * Gets a value indicating if the user is moving the camera
  98290. */
  98291. get: function () {
  98292. if (!this._attachedCamera) {
  98293. return false;
  98294. }
  98295. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98296. this._attachedCamera.inertialBetaOffset !== 0 ||
  98297. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98298. this._attachedCamera.inertialPanningX !== 0 ||
  98299. this._attachedCamera.inertialPanningY !== 0 ||
  98300. this._isPointerDown;
  98301. },
  98302. enumerable: true,
  98303. configurable: true
  98304. });
  98305. /**
  98306. * The easing function used by animations
  98307. */
  98308. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98309. /**
  98310. * The easing mode used by animations
  98311. */
  98312. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98313. // Statics
  98314. /**
  98315. * The camera can move all the way towards the mesh.
  98316. */
  98317. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98318. /**
  98319. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98320. */
  98321. FramingBehavior.FitFrustumSidesMode = 1;
  98322. return FramingBehavior;
  98323. }());
  98324. BABYLON.FramingBehavior = FramingBehavior;
  98325. })(BABYLON || (BABYLON = {}));
  98326. //# sourceMappingURL=babylon.framingBehavior.js.map
  98327. var BABYLON;
  98328. (function (BABYLON) {
  98329. /**
  98330. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98331. */
  98332. var BouncingBehavior = /** @class */ (function () {
  98333. function BouncingBehavior() {
  98334. /**
  98335. * The duration of the animation, in milliseconds
  98336. */
  98337. this.transitionDuration = 450;
  98338. /**
  98339. * Length of the distance animated by the transition when lower radius is reached
  98340. */
  98341. this.lowerRadiusTransitionRange = 2;
  98342. /**
  98343. * Length of the distance animated by the transition when upper radius is reached
  98344. */
  98345. this.upperRadiusTransitionRange = -2;
  98346. this._autoTransitionRange = false;
  98347. // Animations
  98348. this._radiusIsAnimating = false;
  98349. this._radiusBounceTransition = null;
  98350. this._animatables = new Array();
  98351. }
  98352. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98353. get: function () {
  98354. return "Bouncing";
  98355. },
  98356. enumerable: true,
  98357. configurable: true
  98358. });
  98359. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98360. /**
  98361. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98362. */
  98363. get: function () {
  98364. return this._autoTransitionRange;
  98365. },
  98366. /**
  98367. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98368. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98369. */
  98370. set: function (value) {
  98371. var _this = this;
  98372. if (this._autoTransitionRange === value) {
  98373. return;
  98374. }
  98375. this._autoTransitionRange = value;
  98376. var camera = this._attachedCamera;
  98377. if (!camera) {
  98378. return;
  98379. }
  98380. if (value) {
  98381. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98382. if (!mesh) {
  98383. return;
  98384. }
  98385. mesh.computeWorldMatrix(true);
  98386. var diagonal = mesh.getBoundingInfo().diagonalLength;
  98387. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  98388. _this.upperRadiusTransitionRange = diagonal * 0.05;
  98389. });
  98390. }
  98391. else if (this._onMeshTargetChangedObserver) {
  98392. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98393. }
  98394. },
  98395. enumerable: true,
  98396. configurable: true
  98397. });
  98398. BouncingBehavior.prototype.init = function () {
  98399. // Do notihng
  98400. };
  98401. BouncingBehavior.prototype.attach = function (camera) {
  98402. var _this = this;
  98403. this._attachedCamera = camera;
  98404. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98405. if (!_this._attachedCamera) {
  98406. return;
  98407. }
  98408. // Add the bounce animation to the lower radius limit
  98409. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  98410. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  98411. }
  98412. // Add the bounce animation to the upper radius limit
  98413. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  98414. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  98415. }
  98416. });
  98417. };
  98418. BouncingBehavior.prototype.detach = function () {
  98419. if (!this._attachedCamera) {
  98420. return;
  98421. }
  98422. if (this._onAfterCheckInputsObserver) {
  98423. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98424. }
  98425. if (this._onMeshTargetChangedObserver) {
  98426. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98427. }
  98428. this._attachedCamera = null;
  98429. };
  98430. /**
  98431. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  98432. * @param radiusLimit The limit to check against.
  98433. * @return Bool to indicate if at limit.
  98434. */
  98435. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  98436. if (!this._attachedCamera) {
  98437. return false;
  98438. }
  98439. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  98440. return true;
  98441. }
  98442. return false;
  98443. };
  98444. /**
  98445. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  98446. * @param radiusDelta The delta by which to animate to. Can be negative.
  98447. */
  98448. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  98449. var _this = this;
  98450. if (!this._attachedCamera) {
  98451. return;
  98452. }
  98453. if (!this._radiusBounceTransition) {
  98454. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  98455. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  98456. }
  98457. // Prevent zoom until bounce has completed
  98458. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  98459. this._attachedCamera.wheelPrecision = Infinity;
  98460. this._attachedCamera.inertialRadiusOffset = 0;
  98461. // Animate to the radius limit
  98462. this.stopAllAnimations();
  98463. this._radiusIsAnimating = true;
  98464. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  98465. if (animatable) {
  98466. this._animatables.push(animatable);
  98467. }
  98468. };
  98469. /**
  98470. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  98471. */
  98472. BouncingBehavior.prototype._clearAnimationLocks = function () {
  98473. this._radiusIsAnimating = false;
  98474. if (this._attachedCamera) {
  98475. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  98476. }
  98477. };
  98478. /**
  98479. * Stops and removes all animations that have been applied to the camera
  98480. */
  98481. BouncingBehavior.prototype.stopAllAnimations = function () {
  98482. if (this._attachedCamera) {
  98483. this._attachedCamera.animations = [];
  98484. }
  98485. while (this._animatables.length) {
  98486. this._animatables[0].onAnimationEnd = null;
  98487. this._animatables[0].stop();
  98488. this._animatables.shift();
  98489. }
  98490. };
  98491. /**
  98492. * The easing function used by animations
  98493. */
  98494. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  98495. /**
  98496. * The easing mode used by animations
  98497. */
  98498. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  98499. return BouncingBehavior;
  98500. }());
  98501. BABYLON.BouncingBehavior = BouncingBehavior;
  98502. })(BABYLON || (BABYLON = {}));
  98503. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  98504. var BABYLON;
  98505. (function (BABYLON) {
  98506. var AutoRotationBehavior = /** @class */ (function () {
  98507. function AutoRotationBehavior() {
  98508. this._zoomStopsAnimation = false;
  98509. this._idleRotationSpeed = 0.05;
  98510. this._idleRotationWaitTime = 2000;
  98511. this._idleRotationSpinupTime = 2000;
  98512. this._isPointerDown = false;
  98513. this._lastFrameTime = null;
  98514. this._lastInteractionTime = -Infinity;
  98515. this._cameraRotationSpeed = 0;
  98516. this._lastFrameRadius = 0;
  98517. }
  98518. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  98519. get: function () {
  98520. return "AutoRotation";
  98521. },
  98522. enumerable: true,
  98523. configurable: true
  98524. });
  98525. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  98526. /**
  98527. * Gets the flag that indicates if user zooming should stop animation.
  98528. */
  98529. get: function () {
  98530. return this._zoomStopsAnimation;
  98531. },
  98532. /**
  98533. * Sets the flag that indicates if user zooming should stop animation.
  98534. */
  98535. set: function (flag) {
  98536. this._zoomStopsAnimation = flag;
  98537. },
  98538. enumerable: true,
  98539. configurable: true
  98540. });
  98541. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  98542. /**
  98543. * Gets the default speed at which the camera rotates around the model.
  98544. */
  98545. get: function () {
  98546. return this._idleRotationSpeed;
  98547. },
  98548. /**
  98549. * Sets the default speed at which the camera rotates around the model.
  98550. */
  98551. set: function (speed) {
  98552. this._idleRotationSpeed = speed;
  98553. },
  98554. enumerable: true,
  98555. configurable: true
  98556. });
  98557. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  98558. /**
  98559. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  98560. */
  98561. get: function () {
  98562. return this._idleRotationWaitTime;
  98563. },
  98564. /**
  98565. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  98566. */
  98567. set: function (time) {
  98568. this._idleRotationWaitTime = time;
  98569. },
  98570. enumerable: true,
  98571. configurable: true
  98572. });
  98573. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  98574. /**
  98575. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98576. */
  98577. get: function () {
  98578. return this._idleRotationSpinupTime;
  98579. },
  98580. /**
  98581. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  98582. */
  98583. set: function (time) {
  98584. this._idleRotationSpinupTime = time;
  98585. },
  98586. enumerable: true,
  98587. configurable: true
  98588. });
  98589. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  98590. /**
  98591. * Gets a value indicating if the camera is currently rotating because of this behavior
  98592. */
  98593. get: function () {
  98594. return Math.abs(this._cameraRotationSpeed) > 0;
  98595. },
  98596. enumerable: true,
  98597. configurable: true
  98598. });
  98599. AutoRotationBehavior.prototype.init = function () {
  98600. // Do notihng
  98601. };
  98602. AutoRotationBehavior.prototype.attach = function (camera) {
  98603. var _this = this;
  98604. this._attachedCamera = camera;
  98605. var scene = this._attachedCamera.getScene();
  98606. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98607. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98608. _this._isPointerDown = true;
  98609. return;
  98610. }
  98611. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98612. _this._isPointerDown = false;
  98613. }
  98614. });
  98615. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98616. var now = BABYLON.Tools.Now;
  98617. var dt = 0;
  98618. if (_this._lastFrameTime != null) {
  98619. dt = now - _this._lastFrameTime;
  98620. }
  98621. _this._lastFrameTime = now;
  98622. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98623. _this._applyUserInteraction();
  98624. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  98625. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  98626. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  98627. // Step camera rotation by rotation speed
  98628. if (_this._attachedCamera) {
  98629. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  98630. }
  98631. });
  98632. };
  98633. AutoRotationBehavior.prototype.detach = function () {
  98634. if (!this._attachedCamera) {
  98635. return;
  98636. }
  98637. var scene = this._attachedCamera.getScene();
  98638. if (this._onPrePointerObservableObserver) {
  98639. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98640. }
  98641. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98642. this._attachedCamera = null;
  98643. };
  98644. /**
  98645. * Returns true if user is scrolling.
  98646. * @return true if user is scrolling.
  98647. */
  98648. AutoRotationBehavior.prototype._userIsZooming = function () {
  98649. if (!this._attachedCamera) {
  98650. return false;
  98651. }
  98652. return this._attachedCamera.inertialRadiusOffset !== 0;
  98653. };
  98654. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  98655. if (!this._attachedCamera) {
  98656. return false;
  98657. }
  98658. var zoomHasHitLimit = false;
  98659. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  98660. zoomHasHitLimit = true;
  98661. }
  98662. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  98663. this._lastFrameRadius = this._attachedCamera.radius;
  98664. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  98665. };
  98666. /**
  98667. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98668. */
  98669. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  98670. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  98671. this._lastInteractionTime = BABYLON.Tools.Now;
  98672. }
  98673. };
  98674. // Tools
  98675. AutoRotationBehavior.prototype._userIsMoving = function () {
  98676. if (!this._attachedCamera) {
  98677. return false;
  98678. }
  98679. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98680. this._attachedCamera.inertialBetaOffset !== 0 ||
  98681. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98682. this._attachedCamera.inertialPanningX !== 0 ||
  98683. this._attachedCamera.inertialPanningY !== 0 ||
  98684. this._isPointerDown;
  98685. };
  98686. return AutoRotationBehavior;
  98687. }());
  98688. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  98689. })(BABYLON || (BABYLON = {}));
  98690. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  98691. var BABYLON;
  98692. (function (BABYLON) {
  98693. var NullEngineOptions = /** @class */ (function () {
  98694. function NullEngineOptions() {
  98695. this.renderWidth = 512;
  98696. this.renderHeight = 256;
  98697. this.textureSize = 512;
  98698. this.deterministicLockstep = false;
  98699. this.lockstepMaxSteps = 4;
  98700. }
  98701. return NullEngineOptions;
  98702. }());
  98703. BABYLON.NullEngineOptions = NullEngineOptions;
  98704. /**
  98705. * The null engine class provides support for headless version of babylon.js.
  98706. * This can be used in server side scenario or for testing purposes
  98707. */
  98708. var NullEngine = /** @class */ (function (_super) {
  98709. __extends(NullEngine, _super);
  98710. function NullEngine(options) {
  98711. if (options === void 0) { options = new NullEngineOptions(); }
  98712. var _this = _super.call(this, null) || this;
  98713. if (options.deterministicLockstep === undefined) {
  98714. options.deterministicLockstep = false;
  98715. }
  98716. if (options.lockstepMaxSteps === undefined) {
  98717. options.lockstepMaxSteps = 4;
  98718. }
  98719. _this._options = options;
  98720. // Init caps
  98721. // We consider we are on a webgl1 capable device
  98722. _this._caps = new BABYLON.EngineCapabilities();
  98723. _this._caps.maxTexturesImageUnits = 16;
  98724. _this._caps.maxVertexTextureImageUnits = 16;
  98725. _this._caps.maxTextureSize = 512;
  98726. _this._caps.maxCubemapTextureSize = 512;
  98727. _this._caps.maxRenderTextureSize = 512;
  98728. _this._caps.maxVertexAttribs = 16;
  98729. _this._caps.maxVaryingVectors = 16;
  98730. _this._caps.maxFragmentUniformVectors = 16;
  98731. _this._caps.maxVertexUniformVectors = 16;
  98732. // Extensions
  98733. _this._caps.standardDerivatives = false;
  98734. _this._caps.astc = null;
  98735. _this._caps.s3tc = null;
  98736. _this._caps.pvrtc = null;
  98737. _this._caps.etc1 = null;
  98738. _this._caps.etc2 = null;
  98739. _this._caps.textureAnisotropicFilterExtension = null;
  98740. _this._caps.maxAnisotropy = 0;
  98741. _this._caps.uintIndices = false;
  98742. _this._caps.fragmentDepthSupported = false;
  98743. _this._caps.highPrecisionShaderSupported = true;
  98744. _this._caps.colorBufferFloat = false;
  98745. _this._caps.textureFloat = false;
  98746. _this._caps.textureFloatLinearFiltering = false;
  98747. _this._caps.textureFloatRender = false;
  98748. _this._caps.textureHalfFloat = false;
  98749. _this._caps.textureHalfFloatLinearFiltering = false;
  98750. _this._caps.textureHalfFloatRender = false;
  98751. _this._caps.textureLOD = false;
  98752. _this._caps.drawBuffersExtension = false;
  98753. _this._caps.depthTextureExtension = false;
  98754. _this._caps.vertexArrayObject = false;
  98755. _this._caps.instancedArrays = false;
  98756. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  98757. // Wrappers
  98758. if (typeof URL === "undefined") {
  98759. URL = {
  98760. createObjectURL: function () { },
  98761. revokeObjectURL: function () { }
  98762. };
  98763. }
  98764. if (typeof Blob === "undefined") {
  98765. Blob = function () { };
  98766. }
  98767. return _this;
  98768. }
  98769. NullEngine.prototype.isDeterministicLockStep = function () {
  98770. return this._options.deterministicLockstep;
  98771. };
  98772. NullEngine.prototype.getLockstepMaxSteps = function () {
  98773. return this._options.lockstepMaxSteps;
  98774. };
  98775. NullEngine.prototype.getHardwareScalingLevel = function () {
  98776. return 1.0;
  98777. };
  98778. NullEngine.prototype.createVertexBuffer = function (vertices) {
  98779. return {
  98780. capacity: 0,
  98781. references: 1,
  98782. is32Bits: false
  98783. };
  98784. };
  98785. NullEngine.prototype.createIndexBuffer = function (indices) {
  98786. return {
  98787. capacity: 0,
  98788. references: 1,
  98789. is32Bits: false
  98790. };
  98791. };
  98792. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  98793. if (stencil === void 0) { stencil = false; }
  98794. };
  98795. NullEngine.prototype.getRenderWidth = function (useScreen) {
  98796. if (useScreen === void 0) { useScreen = false; }
  98797. if (!useScreen && this._currentRenderTarget) {
  98798. return this._currentRenderTarget.width;
  98799. }
  98800. return this._options.renderWidth;
  98801. };
  98802. NullEngine.prototype.getRenderHeight = function (useScreen) {
  98803. if (useScreen === void 0) { useScreen = false; }
  98804. if (!useScreen && this._currentRenderTarget) {
  98805. return this._currentRenderTarget.height;
  98806. }
  98807. return this._options.renderHeight;
  98808. };
  98809. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  98810. this._cachedViewport = viewport;
  98811. };
  98812. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  98813. return {
  98814. transformFeedback: null,
  98815. __SPECTOR_rebuildProgram: null
  98816. };
  98817. };
  98818. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  98819. return [];
  98820. };
  98821. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  98822. return [];
  98823. };
  98824. NullEngine.prototype.bindSamplers = function (effect) {
  98825. this._currentEffect = null;
  98826. };
  98827. NullEngine.prototype.enableEffect = function (effect) {
  98828. this._currentEffect = effect;
  98829. if (effect.onBind) {
  98830. effect.onBind(effect);
  98831. }
  98832. effect.onBindObservable.notifyObservers(effect);
  98833. };
  98834. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  98835. if (zOffset === void 0) { zOffset = 0; }
  98836. if (reverseSide === void 0) { reverseSide = false; }
  98837. };
  98838. NullEngine.prototype.setIntArray = function (uniform, array) {
  98839. };
  98840. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  98841. };
  98842. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  98843. };
  98844. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  98845. };
  98846. NullEngine.prototype.setFloatArray = function (uniform, array) {
  98847. };
  98848. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  98849. };
  98850. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  98851. };
  98852. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  98853. };
  98854. NullEngine.prototype.setArray = function (uniform, array) {
  98855. };
  98856. NullEngine.prototype.setArray2 = function (uniform, array) {
  98857. };
  98858. NullEngine.prototype.setArray3 = function (uniform, array) {
  98859. };
  98860. NullEngine.prototype.setArray4 = function (uniform, array) {
  98861. };
  98862. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  98863. };
  98864. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  98865. };
  98866. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  98867. };
  98868. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  98869. };
  98870. NullEngine.prototype.setFloat = function (uniform, value) {
  98871. };
  98872. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  98873. };
  98874. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  98875. };
  98876. NullEngine.prototype.setBool = function (uniform, bool) {
  98877. };
  98878. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  98879. };
  98880. NullEngine.prototype.setColor3 = function (uniform, color3) {
  98881. };
  98882. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  98883. };
  98884. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  98885. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  98886. if (this._alphaMode === mode) {
  98887. return;
  98888. }
  98889. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  98890. if (!noDepthWriteChange) {
  98891. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  98892. }
  98893. this._alphaMode = mode;
  98894. };
  98895. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  98896. };
  98897. NullEngine.prototype.wipeCaches = function (bruteForce) {
  98898. if (this.preventCacheWipeBetweenFrames) {
  98899. return;
  98900. }
  98901. this.resetTextureCache();
  98902. this._currentEffect = null;
  98903. if (bruteForce) {
  98904. this._currentProgram = null;
  98905. this._stencilState.reset();
  98906. this._depthCullingState.reset();
  98907. this._alphaState.reset();
  98908. }
  98909. this._cachedVertexBuffers = null;
  98910. this._cachedIndexBuffer = null;
  98911. this._cachedEffectForVertexBuffers = null;
  98912. };
  98913. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  98914. };
  98915. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  98916. };
  98917. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  98918. };
  98919. NullEngine.prototype._createTexture = function () {
  98920. return {};
  98921. };
  98922. NullEngine.prototype._releaseTexture = function (texture) {
  98923. };
  98924. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  98925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  98926. if (onLoad === void 0) { onLoad = null; }
  98927. if (onError === void 0) { onError = null; }
  98928. if (buffer === void 0) { buffer = null; }
  98929. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  98930. var url = String(urlArg);
  98931. texture.url = url;
  98932. texture.generateMipMaps = !noMipmap;
  98933. texture.samplingMode = samplingMode;
  98934. texture.invertY = invertY;
  98935. texture.baseWidth = this._options.textureSize;
  98936. texture.baseHeight = this._options.textureSize;
  98937. texture.width = this._options.textureSize;
  98938. texture.height = this._options.textureSize;
  98939. if (format) {
  98940. texture.format = format;
  98941. }
  98942. texture.isReady = true;
  98943. if (onLoad) {
  98944. onLoad();
  98945. }
  98946. this._internalTexturesCache.push(texture);
  98947. return texture;
  98948. };
  98949. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  98950. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  98951. if (options !== undefined && typeof options === "object") {
  98952. fullOptions.generateMipMaps = options.generateMipMaps;
  98953. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  98954. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  98955. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  98956. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  98957. }
  98958. else {
  98959. fullOptions.generateMipMaps = options;
  98960. fullOptions.generateDepthBuffer = true;
  98961. fullOptions.generateStencilBuffer = false;
  98962. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98963. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  98964. }
  98965. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  98966. var width = size.width || size;
  98967. var height = size.height || size;
  98968. texture._depthStencilBuffer = {};
  98969. texture._framebuffer = {};
  98970. texture.baseWidth = width;
  98971. texture.baseHeight = height;
  98972. texture.width = width;
  98973. texture.height = height;
  98974. texture.isReady = true;
  98975. texture.samples = 1;
  98976. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  98977. texture.samplingMode = fullOptions.samplingMode;
  98978. texture.type = fullOptions.type;
  98979. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  98980. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  98981. this._internalTexturesCache.push(texture);
  98982. return texture;
  98983. };
  98984. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  98985. texture.samplingMode = samplingMode;
  98986. };
  98987. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  98988. if (this._currentRenderTarget) {
  98989. this.unBindFramebuffer(this._currentRenderTarget);
  98990. }
  98991. this._currentRenderTarget = texture;
  98992. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  98993. if (this._cachedViewport && !forceFullscreenViewport) {
  98994. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  98995. }
  98996. };
  98997. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  98998. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  98999. this._currentRenderTarget = null;
  99000. if (onBeforeUnbind) {
  99001. if (texture._MSAAFramebuffer) {
  99002. this._currentFramebuffer = texture._framebuffer;
  99003. }
  99004. onBeforeUnbind();
  99005. }
  99006. this._currentFramebuffer = null;
  99007. };
  99008. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99009. var vbo = {
  99010. capacity: 1,
  99011. references: 1,
  99012. is32Bits: false
  99013. };
  99014. return vbo;
  99015. };
  99016. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99017. if (offset === void 0) { offset = 0; }
  99018. };
  99019. /**
  99020. * Updates a dynamic vertex buffer.
  99021. * @param vertexBuffer the vertex buffer to update
  99022. * @param data the data used to update the vertex buffer
  99023. * @param byteOffset the byte offset of the data (optional)
  99024. * @param byteLength the byte length of the data (optional)
  99025. */
  99026. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99027. };
  99028. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99029. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99030. this._boundTexturesCache[this._activeChannel] = texture;
  99031. return true;
  99032. }
  99033. return false;
  99034. };
  99035. NullEngine.prototype._bindTexture = function (channel, texture) {
  99036. if (channel < 0) {
  99037. return;
  99038. }
  99039. this._bindTextureDirectly(0, texture);
  99040. };
  99041. NullEngine.prototype._releaseBuffer = function (buffer) {
  99042. buffer.references--;
  99043. if (buffer.references === 0) {
  99044. return true;
  99045. }
  99046. return false;
  99047. };
  99048. NullEngine.prototype.releaseEffects = function () {
  99049. };
  99050. return NullEngine;
  99051. }(BABYLON.Engine));
  99052. BABYLON.NullEngine = NullEngine;
  99053. })(BABYLON || (BABYLON = {}));
  99054. //# sourceMappingURL=babylon.nullEngine.js.map
  99055. var BABYLON;
  99056. (function (BABYLON) {
  99057. /**
  99058. * This class can be used to get instrumentation data from a Babylon engine
  99059. */
  99060. var EngineInstrumentation = /** @class */ (function () {
  99061. function EngineInstrumentation(engine) {
  99062. this.engine = engine;
  99063. this._captureGPUFrameTime = false;
  99064. this._gpuFrameTime = new BABYLON.PerfCounter();
  99065. this._captureShaderCompilationTime = false;
  99066. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99067. // Observers
  99068. this._onBeginFrameObserver = null;
  99069. this._onEndFrameObserver = null;
  99070. this._onBeforeShaderCompilationObserver = null;
  99071. this._onAfterShaderCompilationObserver = null;
  99072. }
  99073. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99074. // Properties
  99075. /**
  99076. * Gets the perf counter used for GPU frame time
  99077. */
  99078. get: function () {
  99079. return this._gpuFrameTime;
  99080. },
  99081. enumerable: true,
  99082. configurable: true
  99083. });
  99084. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99085. /**
  99086. * Gets the GPU frame time capture status
  99087. */
  99088. get: function () {
  99089. return this._captureGPUFrameTime;
  99090. },
  99091. /**
  99092. * Enable or disable the GPU frame time capture
  99093. */
  99094. set: function (value) {
  99095. var _this = this;
  99096. if (value === this._captureGPUFrameTime) {
  99097. return;
  99098. }
  99099. this._captureGPUFrameTime = value;
  99100. if (value) {
  99101. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99102. if (!_this._gpuFrameTimeToken) {
  99103. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99104. }
  99105. });
  99106. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99107. if (!_this._gpuFrameTimeToken) {
  99108. return;
  99109. }
  99110. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99111. if (time > -1) {
  99112. _this._gpuFrameTimeToken = null;
  99113. _this._gpuFrameTime.fetchNewFrame();
  99114. _this._gpuFrameTime.addCount(time, true);
  99115. }
  99116. });
  99117. }
  99118. else {
  99119. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99120. this._onBeginFrameObserver = null;
  99121. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99122. this._onEndFrameObserver = null;
  99123. }
  99124. },
  99125. enumerable: true,
  99126. configurable: true
  99127. });
  99128. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99129. /**
  99130. * Gets the perf counter used for shader compilation time
  99131. */
  99132. get: function () {
  99133. return this._shaderCompilationTime;
  99134. },
  99135. enumerable: true,
  99136. configurable: true
  99137. });
  99138. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99139. /**
  99140. * Gets the shader compilation time capture status
  99141. */
  99142. get: function () {
  99143. return this._captureShaderCompilationTime;
  99144. },
  99145. /**
  99146. * Enable or disable the shader compilation time capture
  99147. */
  99148. set: function (value) {
  99149. var _this = this;
  99150. if (value === this._captureShaderCompilationTime) {
  99151. return;
  99152. }
  99153. this._captureShaderCompilationTime = value;
  99154. if (value) {
  99155. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99156. _this._shaderCompilationTime.fetchNewFrame();
  99157. _this._shaderCompilationTime.beginMonitoring();
  99158. });
  99159. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99160. _this._shaderCompilationTime.endMonitoring();
  99161. });
  99162. }
  99163. else {
  99164. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99165. this._onBeforeShaderCompilationObserver = null;
  99166. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99167. this._onAfterShaderCompilationObserver = null;
  99168. }
  99169. },
  99170. enumerable: true,
  99171. configurable: true
  99172. });
  99173. EngineInstrumentation.prototype.dispose = function () {
  99174. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99175. this._onBeginFrameObserver = null;
  99176. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99177. this._onEndFrameObserver = null;
  99178. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99179. this._onBeforeShaderCompilationObserver = null;
  99180. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99181. this._onAfterShaderCompilationObserver = null;
  99182. this.engine = null;
  99183. };
  99184. return EngineInstrumentation;
  99185. }());
  99186. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99187. })(BABYLON || (BABYLON = {}));
  99188. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99189. var BABYLON;
  99190. (function (BABYLON) {
  99191. /**
  99192. * This class can be used to get instrumentation data from a Babylon engine
  99193. */
  99194. var SceneInstrumentation = /** @class */ (function () {
  99195. function SceneInstrumentation(scene) {
  99196. var _this = this;
  99197. this.scene = scene;
  99198. this._captureActiveMeshesEvaluationTime = false;
  99199. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99200. this._captureRenderTargetsRenderTime = false;
  99201. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99202. this._captureFrameTime = false;
  99203. this._frameTime = new BABYLON.PerfCounter();
  99204. this._captureRenderTime = false;
  99205. this._renderTime = new BABYLON.PerfCounter();
  99206. this._captureInterFrameTime = false;
  99207. this._interFrameTime = new BABYLON.PerfCounter();
  99208. this._captureParticlesRenderTime = false;
  99209. this._particlesRenderTime = new BABYLON.PerfCounter();
  99210. this._captureSpritesRenderTime = false;
  99211. this._spritesRenderTime = new BABYLON.PerfCounter();
  99212. this._capturePhysicsTime = false;
  99213. this._physicsTime = new BABYLON.PerfCounter();
  99214. this._captureAnimationsTime = false;
  99215. this._animationsTime = new BABYLON.PerfCounter();
  99216. this._captureCameraRenderTime = false;
  99217. this._cameraRenderTime = new BABYLON.PerfCounter();
  99218. // Observers
  99219. this._onBeforeActiveMeshesEvaluationObserver = null;
  99220. this._onAfterActiveMeshesEvaluationObserver = null;
  99221. this._onBeforeRenderTargetsRenderObserver = null;
  99222. this._onAfterRenderTargetsRenderObserver = null;
  99223. this._onAfterRenderObserver = null;
  99224. this._onBeforeDrawPhaseObserver = null;
  99225. this._onAfterDrawPhaseObserver = null;
  99226. this._onBeforeAnimationsObserver = null;
  99227. this._onBeforeParticlesRenderingObserver = null;
  99228. this._onAfterParticlesRenderingObserver = null;
  99229. this._onBeforeSpritesRenderingObserver = null;
  99230. this._onAfterSpritesRenderingObserver = null;
  99231. this._onBeforePhysicsObserver = null;
  99232. this._onAfterPhysicsObserver = null;
  99233. this._onAfterAnimationsObserver = null;
  99234. this._onBeforeCameraRenderObserver = null;
  99235. this._onAfterCameraRenderObserver = null;
  99236. // Before render
  99237. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99238. if (_this._captureActiveMeshesEvaluationTime) {
  99239. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99240. }
  99241. if (_this._captureRenderTargetsRenderTime) {
  99242. _this._renderTargetsRenderTime.fetchNewFrame();
  99243. }
  99244. if (_this._captureFrameTime) {
  99245. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99246. _this._frameTime.beginMonitoring();
  99247. }
  99248. if (_this._captureInterFrameTime) {
  99249. _this._interFrameTime.endMonitoring();
  99250. }
  99251. if (_this._captureParticlesRenderTime) {
  99252. _this._particlesRenderTime.fetchNewFrame();
  99253. }
  99254. if (_this._captureSpritesRenderTime) {
  99255. _this._spritesRenderTime.fetchNewFrame();
  99256. }
  99257. if (_this._captureAnimationsTime) {
  99258. _this._animationsTime.beginMonitoring();
  99259. }
  99260. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99261. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99262. });
  99263. // After render
  99264. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99265. if (_this._captureFrameTime) {
  99266. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99267. _this._frameTime.endMonitoring();
  99268. }
  99269. if (_this._captureRenderTime) {
  99270. _this._renderTime.endMonitoring(false);
  99271. }
  99272. if (_this._captureInterFrameTime) {
  99273. _this._interFrameTime.beginMonitoring();
  99274. }
  99275. });
  99276. }
  99277. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99278. // Properties
  99279. /**
  99280. * Gets the perf counter used for active meshes evaluation time
  99281. */
  99282. get: function () {
  99283. return this._activeMeshesEvaluationTime;
  99284. },
  99285. enumerable: true,
  99286. configurable: true
  99287. });
  99288. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99289. /**
  99290. * Gets the active meshes evaluation time capture status
  99291. */
  99292. get: function () {
  99293. return this._captureActiveMeshesEvaluationTime;
  99294. },
  99295. /**
  99296. * Enable or disable the active meshes evaluation time capture
  99297. */
  99298. set: function (value) {
  99299. var _this = this;
  99300. if (value === this._captureActiveMeshesEvaluationTime) {
  99301. return;
  99302. }
  99303. this._captureActiveMeshesEvaluationTime = value;
  99304. if (value) {
  99305. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99306. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99307. _this._activeMeshesEvaluationTime.beginMonitoring();
  99308. });
  99309. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99310. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99311. _this._activeMeshesEvaluationTime.endMonitoring();
  99312. });
  99313. }
  99314. else {
  99315. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99316. this._onBeforeActiveMeshesEvaluationObserver = null;
  99317. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99318. this._onAfterActiveMeshesEvaluationObserver = null;
  99319. }
  99320. },
  99321. enumerable: true,
  99322. configurable: true
  99323. });
  99324. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99325. /**
  99326. * Gets the perf counter used for render targets render time
  99327. */
  99328. get: function () {
  99329. return this._renderTargetsRenderTime;
  99330. },
  99331. enumerable: true,
  99332. configurable: true
  99333. });
  99334. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99335. /**
  99336. * Gets the render targets render time capture status
  99337. */
  99338. get: function () {
  99339. return this._captureRenderTargetsRenderTime;
  99340. },
  99341. /**
  99342. * Enable or disable the render targets render time capture
  99343. */
  99344. set: function (value) {
  99345. var _this = this;
  99346. if (value === this._captureRenderTargetsRenderTime) {
  99347. return;
  99348. }
  99349. this._captureRenderTargetsRenderTime = value;
  99350. if (value) {
  99351. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99352. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99353. _this._renderTargetsRenderTime.beginMonitoring();
  99354. });
  99355. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99356. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99357. _this._renderTargetsRenderTime.endMonitoring(false);
  99358. });
  99359. }
  99360. else {
  99361. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99362. this._onBeforeRenderTargetsRenderObserver = null;
  99363. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99364. this._onAfterRenderTargetsRenderObserver = null;
  99365. }
  99366. },
  99367. enumerable: true,
  99368. configurable: true
  99369. });
  99370. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99371. /**
  99372. * Gets the perf counter used for particles render time
  99373. */
  99374. get: function () {
  99375. return this._particlesRenderTime;
  99376. },
  99377. enumerable: true,
  99378. configurable: true
  99379. });
  99380. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99381. /**
  99382. * Gets the particles render time capture status
  99383. */
  99384. get: function () {
  99385. return this._captureParticlesRenderTime;
  99386. },
  99387. /**
  99388. * Enable or disable the particles render time capture
  99389. */
  99390. set: function (value) {
  99391. var _this = this;
  99392. if (value === this._captureParticlesRenderTime) {
  99393. return;
  99394. }
  99395. this._captureParticlesRenderTime = value;
  99396. if (value) {
  99397. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  99398. BABYLON.Tools.StartPerformanceCounter("Particles");
  99399. _this._particlesRenderTime.beginMonitoring();
  99400. });
  99401. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  99402. BABYLON.Tools.EndPerformanceCounter("Particles");
  99403. _this._particlesRenderTime.endMonitoring(false);
  99404. });
  99405. }
  99406. else {
  99407. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99408. this._onBeforeParticlesRenderingObserver = null;
  99409. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99410. this._onAfterParticlesRenderingObserver = null;
  99411. }
  99412. },
  99413. enumerable: true,
  99414. configurable: true
  99415. });
  99416. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  99417. /**
  99418. * Gets the perf counter used for sprites render time
  99419. */
  99420. get: function () {
  99421. return this._spritesRenderTime;
  99422. },
  99423. enumerable: true,
  99424. configurable: true
  99425. });
  99426. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  99427. /**
  99428. * Gets the sprites render time capture status
  99429. */
  99430. get: function () {
  99431. return this._captureSpritesRenderTime;
  99432. },
  99433. /**
  99434. * Enable or disable the sprites render time capture
  99435. */
  99436. set: function (value) {
  99437. var _this = this;
  99438. if (value === this._captureSpritesRenderTime) {
  99439. return;
  99440. }
  99441. this._captureSpritesRenderTime = value;
  99442. if (value) {
  99443. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  99444. BABYLON.Tools.StartPerformanceCounter("Sprites");
  99445. _this._spritesRenderTime.beginMonitoring();
  99446. });
  99447. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  99448. BABYLON.Tools.EndPerformanceCounter("Sprites");
  99449. _this._spritesRenderTime.endMonitoring(false);
  99450. });
  99451. }
  99452. else {
  99453. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99454. this._onBeforeSpritesRenderingObserver = null;
  99455. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99456. this._onAfterSpritesRenderingObserver = null;
  99457. }
  99458. },
  99459. enumerable: true,
  99460. configurable: true
  99461. });
  99462. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  99463. /**
  99464. * Gets the perf counter used for physics time
  99465. */
  99466. get: function () {
  99467. return this._physicsTime;
  99468. },
  99469. enumerable: true,
  99470. configurable: true
  99471. });
  99472. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  99473. /**
  99474. * Gets the physics time capture status
  99475. */
  99476. get: function () {
  99477. return this._capturePhysicsTime;
  99478. },
  99479. /**
  99480. * Enable or disable the physics time capture
  99481. */
  99482. set: function (value) {
  99483. var _this = this;
  99484. if (value === this._capturePhysicsTime) {
  99485. return;
  99486. }
  99487. this._capturePhysicsTime = value;
  99488. if (value) {
  99489. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  99490. BABYLON.Tools.StartPerformanceCounter("Physics");
  99491. _this._physicsTime.beginMonitoring();
  99492. });
  99493. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  99494. BABYLON.Tools.EndPerformanceCounter("Physics");
  99495. _this._physicsTime.endMonitoring();
  99496. });
  99497. }
  99498. else {
  99499. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99500. this._onBeforePhysicsObserver = null;
  99501. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99502. this._onAfterPhysicsObserver = null;
  99503. }
  99504. },
  99505. enumerable: true,
  99506. configurable: true
  99507. });
  99508. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  99509. /**
  99510. * Gets the perf counter used for animations time
  99511. */
  99512. get: function () {
  99513. return this._animationsTime;
  99514. },
  99515. enumerable: true,
  99516. configurable: true
  99517. });
  99518. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  99519. /**
  99520. * Gets the animations time capture status
  99521. */
  99522. get: function () {
  99523. return this._captureAnimationsTime;
  99524. },
  99525. /**
  99526. * Enable or disable the animations time capture
  99527. */
  99528. set: function (value) {
  99529. var _this = this;
  99530. if (value === this._captureAnimationsTime) {
  99531. return;
  99532. }
  99533. this._captureAnimationsTime = value;
  99534. if (value) {
  99535. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  99536. _this._animationsTime.endMonitoring();
  99537. });
  99538. }
  99539. else {
  99540. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99541. this._onAfterAnimationsObserver = null;
  99542. }
  99543. },
  99544. enumerable: true,
  99545. configurable: true
  99546. });
  99547. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  99548. /**
  99549. * Gets the perf counter used for frame time capture
  99550. */
  99551. get: function () {
  99552. return this._frameTime;
  99553. },
  99554. enumerable: true,
  99555. configurable: true
  99556. });
  99557. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  99558. /**
  99559. * Gets the frame time capture status
  99560. */
  99561. get: function () {
  99562. return this._captureFrameTime;
  99563. },
  99564. /**
  99565. * Enable or disable the frame time capture
  99566. */
  99567. set: function (value) {
  99568. this._captureFrameTime = value;
  99569. },
  99570. enumerable: true,
  99571. configurable: true
  99572. });
  99573. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  99574. /**
  99575. * Gets the perf counter used for inter-frames time capture
  99576. */
  99577. get: function () {
  99578. return this._interFrameTime;
  99579. },
  99580. enumerable: true,
  99581. configurable: true
  99582. });
  99583. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  99584. /**
  99585. * Gets the inter-frames time capture status
  99586. */
  99587. get: function () {
  99588. return this._captureInterFrameTime;
  99589. },
  99590. /**
  99591. * Enable or disable the inter-frames time capture
  99592. */
  99593. set: function (value) {
  99594. this._captureInterFrameTime = value;
  99595. },
  99596. enumerable: true,
  99597. configurable: true
  99598. });
  99599. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  99600. /**
  99601. * Gets the perf counter used for render time capture
  99602. */
  99603. get: function () {
  99604. return this._renderTime;
  99605. },
  99606. enumerable: true,
  99607. configurable: true
  99608. });
  99609. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  99610. /**
  99611. * Gets the render time capture status
  99612. */
  99613. get: function () {
  99614. return this._captureRenderTime;
  99615. },
  99616. /**
  99617. * Enable or disable the render time capture
  99618. */
  99619. set: function (value) {
  99620. var _this = this;
  99621. if (value === this._captureRenderTime) {
  99622. return;
  99623. }
  99624. this._captureRenderTime = value;
  99625. if (value) {
  99626. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  99627. _this._renderTime.beginMonitoring();
  99628. BABYLON.Tools.StartPerformanceCounter("Main render");
  99629. });
  99630. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  99631. _this._renderTime.endMonitoring(false);
  99632. BABYLON.Tools.EndPerformanceCounter("Main render");
  99633. });
  99634. }
  99635. else {
  99636. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99637. this._onBeforeDrawPhaseObserver = null;
  99638. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99639. this._onAfterDrawPhaseObserver = null;
  99640. }
  99641. },
  99642. enumerable: true,
  99643. configurable: true
  99644. });
  99645. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  99646. /**
  99647. * Gets the perf counter used for camera render time capture
  99648. */
  99649. get: function () {
  99650. return this._cameraRenderTime;
  99651. },
  99652. enumerable: true,
  99653. configurable: true
  99654. });
  99655. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  99656. /**
  99657. * Gets the camera render time capture status
  99658. */
  99659. get: function () {
  99660. return this._captureCameraRenderTime;
  99661. },
  99662. /**
  99663. * Enable or disable the camera render time capture
  99664. */
  99665. set: function (value) {
  99666. var _this = this;
  99667. if (value === this._captureCameraRenderTime) {
  99668. return;
  99669. }
  99670. this._captureCameraRenderTime = value;
  99671. if (value) {
  99672. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  99673. _this._cameraRenderTime.beginMonitoring();
  99674. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  99675. });
  99676. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  99677. _this._cameraRenderTime.endMonitoring(false);
  99678. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  99679. });
  99680. }
  99681. else {
  99682. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99683. this._onBeforeCameraRenderObserver = null;
  99684. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99685. this._onAfterCameraRenderObserver = null;
  99686. }
  99687. },
  99688. enumerable: true,
  99689. configurable: true
  99690. });
  99691. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  99692. /**
  99693. * Gets the perf counter used for draw calls
  99694. */
  99695. get: function () {
  99696. return this.scene.getEngine()._drawCalls;
  99697. },
  99698. enumerable: true,
  99699. configurable: true
  99700. });
  99701. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  99702. /**
  99703. * Gets the perf counter used for texture collisions
  99704. */
  99705. get: function () {
  99706. return this.scene.getEngine()._textureCollisions;
  99707. },
  99708. enumerable: true,
  99709. configurable: true
  99710. });
  99711. SceneInstrumentation.prototype.dispose = function () {
  99712. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  99713. this._onAfterRenderObserver = null;
  99714. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99715. this._onBeforeActiveMeshesEvaluationObserver = null;
  99716. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99717. this._onAfterActiveMeshesEvaluationObserver = null;
  99718. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99719. this._onBeforeRenderTargetsRenderObserver = null;
  99720. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99721. this._onAfterRenderTargetsRenderObserver = null;
  99722. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  99723. this._onBeforeAnimationsObserver = null;
  99724. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  99725. this._onBeforeParticlesRenderingObserver = null;
  99726. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  99727. this._onAfterParticlesRenderingObserver = null;
  99728. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  99729. this._onBeforeSpritesRenderingObserver = null;
  99730. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  99731. this._onAfterSpritesRenderingObserver = null;
  99732. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  99733. this._onBeforeDrawPhaseObserver = null;
  99734. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  99735. this._onAfterDrawPhaseObserver = null;
  99736. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  99737. this._onBeforePhysicsObserver = null;
  99738. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  99739. this._onAfterPhysicsObserver = null;
  99740. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  99741. this._onAfterAnimationsObserver = null;
  99742. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  99743. this._onBeforeCameraRenderObserver = null;
  99744. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  99745. this._onAfterCameraRenderObserver = null;
  99746. this.scene = null;
  99747. };
  99748. return SceneInstrumentation;
  99749. }());
  99750. BABYLON.SceneInstrumentation = SceneInstrumentation;
  99751. })(BABYLON || (BABYLON = {}));
  99752. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  99753. var BABYLON;
  99754. (function (BABYLON) {
  99755. /**
  99756. * @hidden
  99757. **/
  99758. var _TimeToken = /** @class */ (function () {
  99759. function _TimeToken() {
  99760. this._timeElapsedQueryEnded = false;
  99761. }
  99762. return _TimeToken;
  99763. }());
  99764. BABYLON._TimeToken = _TimeToken;
  99765. })(BABYLON || (BABYLON = {}));
  99766. //# sourceMappingURL=babylon.timeToken.js.map
  99767. var BABYLON;
  99768. (function (BABYLON) {
  99769. /**
  99770. * Background material defines definition.
  99771. * @hidden Mainly internal Use
  99772. */
  99773. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  99774. __extends(BackgroundMaterialDefines, _super);
  99775. /**
  99776. * Constructor of the defines.
  99777. */
  99778. function BackgroundMaterialDefines() {
  99779. var _this = _super.call(this) || this;
  99780. /**
  99781. * True if the diffuse texture is in use.
  99782. */
  99783. _this.DIFFUSE = false;
  99784. /**
  99785. * The direct UV channel to use.
  99786. */
  99787. _this.DIFFUSEDIRECTUV = 0;
  99788. /**
  99789. * True if the diffuse texture is in gamma space.
  99790. */
  99791. _this.GAMMADIFFUSE = false;
  99792. /**
  99793. * True if the diffuse texture has opacity in the alpha channel.
  99794. */
  99795. _this.DIFFUSEHASALPHA = false;
  99796. /**
  99797. * True if you want the material to fade to transparent at grazing angle.
  99798. */
  99799. _this.OPACITYFRESNEL = false;
  99800. /**
  99801. * True if an extra blur needs to be added in the reflection.
  99802. */
  99803. _this.REFLECTIONBLUR = false;
  99804. /**
  99805. * True if you want the material to fade to reflection at grazing angle.
  99806. */
  99807. _this.REFLECTIONFRESNEL = false;
  99808. /**
  99809. * True if you want the material to falloff as far as you move away from the scene center.
  99810. */
  99811. _this.REFLECTIONFALLOFF = false;
  99812. /**
  99813. * False if the current Webgl implementation does not support the texture lod extension.
  99814. */
  99815. _this.TEXTURELODSUPPORT = false;
  99816. /**
  99817. * True to ensure the data are premultiplied.
  99818. */
  99819. _this.PREMULTIPLYALPHA = false;
  99820. /**
  99821. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  99822. */
  99823. _this.USERGBCOLOR = false;
  99824. /**
  99825. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  99826. * stays aligned with the desired configuration.
  99827. */
  99828. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  99829. /**
  99830. * True to add noise in order to reduce the banding effect.
  99831. */
  99832. _this.NOISE = false;
  99833. /**
  99834. * is the reflection texture in BGR color scheme?
  99835. * Mainly used to solve a bug in ios10 video tag
  99836. */
  99837. _this.REFLECTIONBGR = false;
  99838. _this.IMAGEPROCESSING = false;
  99839. _this.VIGNETTE = false;
  99840. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  99841. _this.VIGNETTEBLENDMODEOPAQUE = false;
  99842. _this.TONEMAPPING = false;
  99843. _this.CONTRAST = false;
  99844. _this.COLORCURVES = false;
  99845. _this.COLORGRADING = false;
  99846. _this.COLORGRADING3D = false;
  99847. _this.SAMPLER3DGREENDEPTH = false;
  99848. _this.SAMPLER3DBGRMAP = false;
  99849. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  99850. _this.EXPOSURE = false;
  99851. // Reflection.
  99852. _this.REFLECTION = false;
  99853. _this.REFLECTIONMAP_3D = false;
  99854. _this.REFLECTIONMAP_SPHERICAL = false;
  99855. _this.REFLECTIONMAP_PLANAR = false;
  99856. _this.REFLECTIONMAP_CUBIC = false;
  99857. _this.REFLECTIONMAP_PROJECTION = false;
  99858. _this.REFLECTIONMAP_SKYBOX = false;
  99859. _this.REFLECTIONMAP_EXPLICIT = false;
  99860. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  99861. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  99862. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  99863. _this.INVERTCUBICMAP = false;
  99864. _this.REFLECTIONMAP_OPPOSITEZ = false;
  99865. _this.LODINREFLECTIONALPHA = false;
  99866. _this.GAMMAREFLECTION = false;
  99867. _this.RGBDREFLECTION = false;
  99868. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  99869. // Default BJS.
  99870. _this.MAINUV1 = false;
  99871. _this.MAINUV2 = false;
  99872. _this.UV1 = false;
  99873. _this.UV2 = false;
  99874. _this.CLIPPLANE = false;
  99875. _this.POINTSIZE = false;
  99876. _this.FOG = false;
  99877. _this.NORMAL = false;
  99878. _this.NUM_BONE_INFLUENCERS = 0;
  99879. _this.BonesPerMesh = 0;
  99880. _this.INSTANCES = false;
  99881. _this.SHADOWFLOAT = false;
  99882. _this.rebuild();
  99883. return _this;
  99884. }
  99885. return BackgroundMaterialDefines;
  99886. }(BABYLON.MaterialDefines));
  99887. /**
  99888. * Background material used to create an efficient environement around your scene.
  99889. */
  99890. var BackgroundMaterial = /** @class */ (function (_super) {
  99891. __extends(BackgroundMaterial, _super);
  99892. /**
  99893. * Instantiates a Background Material in the given scene
  99894. * @param name The friendly name of the material
  99895. * @param scene The scene to add the material to
  99896. */
  99897. function BackgroundMaterial(name, scene) {
  99898. var _this = _super.call(this, name, scene) || this;
  99899. /**
  99900. * Key light Color (multiply against the environement texture)
  99901. */
  99902. _this.primaryColor = BABYLON.Color3.White();
  99903. _this._primaryColorShadowLevel = 0;
  99904. _this._primaryColorHighlightLevel = 0;
  99905. /**
  99906. * Reflection Texture used in the material.
  99907. * Should be author in a specific way for the best result (refer to the documentation).
  99908. */
  99909. _this.reflectionTexture = null;
  99910. /**
  99911. * Reflection Texture level of blur.
  99912. *
  99913. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  99914. * texture twice.
  99915. */
  99916. _this.reflectionBlur = 0;
  99917. /**
  99918. * Diffuse Texture used in the material.
  99919. * Should be author in a specific way for the best result (refer to the documentation).
  99920. */
  99921. _this.diffuseTexture = null;
  99922. _this._shadowLights = null;
  99923. /**
  99924. * Specify the list of lights casting shadow on the material.
  99925. * All scene shadow lights will be included if null.
  99926. */
  99927. _this.shadowLights = null;
  99928. /**
  99929. * Helps adjusting the shadow to a softer level if required.
  99930. * 0 means black shadows and 1 means no shadows.
  99931. */
  99932. _this.shadowLevel = 0;
  99933. /**
  99934. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  99935. * It is usually zero but might be interesting to modify according to your setup.
  99936. */
  99937. _this.sceneCenter = BABYLON.Vector3.Zero();
  99938. /**
  99939. * This helps specifying that the material is falling off to the sky box at grazing angle.
  99940. * This helps ensuring a nice transition when the camera goes under the ground.
  99941. */
  99942. _this.opacityFresnel = true;
  99943. /**
  99944. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  99945. * This helps adding a mirror texture on the ground.
  99946. */
  99947. _this.reflectionFresnel = false;
  99948. /**
  99949. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  99950. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  99951. */
  99952. _this.reflectionFalloffDistance = 0.0;
  99953. /**
  99954. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  99955. */
  99956. _this.reflectionAmount = 1.0;
  99957. /**
  99958. * This specifies the weight of the reflection at grazing angle.
  99959. */
  99960. _this.reflectionReflectance0 = 0.05;
  99961. /**
  99962. * This specifies the weight of the reflection at a perpendicular point of view.
  99963. */
  99964. _this.reflectionReflectance90 = 0.5;
  99965. /**
  99966. * Helps to directly use the maps channels instead of their level.
  99967. */
  99968. _this.useRGBColor = true;
  99969. /**
  99970. * This helps reducing the banding effect that could occur on the background.
  99971. */
  99972. _this.enableNoise = false;
  99973. _this._fovMultiplier = 1.0;
  99974. /**
  99975. * Enable the FOV adjustment feature controlled by fovMultiplier.
  99976. */
  99977. _this.useEquirectangularFOV = false;
  99978. _this._maxSimultaneousLights = 4;
  99979. /**
  99980. * Number of Simultaneous lights allowed on the material.
  99981. */
  99982. _this.maxSimultaneousLights = 4;
  99983. /**
  99984. * Keep track of the image processing observer to allow dispose and replace.
  99985. */
  99986. _this._imageProcessingObserver = null;
  99987. /**
  99988. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  99989. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  99990. */
  99991. _this.switchToBGR = false;
  99992. // Temp values kept as cache in the material.
  99993. _this._renderTargets = new BABYLON.SmartArray(16);
  99994. _this._reflectionControls = BABYLON.Vector4.Zero();
  99995. _this._white = BABYLON.Color3.White();
  99996. _this._primaryShadowColor = BABYLON.Color3.Black();
  99997. _this._primaryHighlightColor = BABYLON.Color3.Black();
  99998. // Setup the default processing configuration to the scene.
  99999. _this._attachImageProcessingConfiguration(null);
  100000. _this.getRenderTargetTextures = function () {
  100001. _this._renderTargets.reset();
  100002. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100003. _this._renderTargets.push(_this._diffuseTexture);
  100004. }
  100005. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100006. _this._renderTargets.push(_this._reflectionTexture);
  100007. }
  100008. return _this._renderTargets;
  100009. };
  100010. return _this;
  100011. }
  100012. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100013. /**
  100014. * Experimental Internal Use Only.
  100015. *
  100016. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100017. * This acts as a helper to set the primary color to a more "human friendly" value.
  100018. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100019. * output color as close as possible from the chosen value.
  100020. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100021. * part of lighting setup.)
  100022. */
  100023. get: function () {
  100024. return this.__perceptualColor;
  100025. },
  100026. set: function (value) {
  100027. this.__perceptualColor = value;
  100028. this._computePrimaryColorFromPerceptualColor();
  100029. this._markAllSubMeshesAsLightsDirty();
  100030. },
  100031. enumerable: true,
  100032. configurable: true
  100033. });
  100034. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100035. /**
  100036. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100037. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100038. */
  100039. get: function () {
  100040. return this._primaryColorShadowLevel;
  100041. },
  100042. set: function (value) {
  100043. this._primaryColorShadowLevel = value;
  100044. this._computePrimaryColors();
  100045. this._markAllSubMeshesAsLightsDirty();
  100046. },
  100047. enumerable: true,
  100048. configurable: true
  100049. });
  100050. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100051. /**
  100052. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100053. * The primary color is used at the level chosen to define what the white area would look.
  100054. */
  100055. get: function () {
  100056. return this._primaryColorHighlightLevel;
  100057. },
  100058. set: function (value) {
  100059. this._primaryColorHighlightLevel = value;
  100060. this._computePrimaryColors();
  100061. this._markAllSubMeshesAsLightsDirty();
  100062. },
  100063. enumerable: true,
  100064. configurable: true
  100065. });
  100066. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100067. /**
  100068. * Sets the reflection reflectance fresnel values according to the default standard
  100069. * empirically know to work well :-)
  100070. */
  100071. set: function (value) {
  100072. var reflectionWeight = value;
  100073. if (reflectionWeight < 0.5) {
  100074. reflectionWeight = reflectionWeight * 2.0;
  100075. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100076. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100077. }
  100078. else {
  100079. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100080. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100081. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100082. }
  100083. },
  100084. enumerable: true,
  100085. configurable: true
  100086. });
  100087. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100088. /**
  100089. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100090. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100091. * Recommended to be keep at 1.0 except for special cases.
  100092. */
  100093. get: function () {
  100094. return this._fovMultiplier;
  100095. },
  100096. set: function (value) {
  100097. if (isNaN(value)) {
  100098. value = 1.0;
  100099. }
  100100. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100101. },
  100102. enumerable: true,
  100103. configurable: true
  100104. });
  100105. /**
  100106. * Attaches a new image processing configuration to the PBR Material.
  100107. * @param configuration (if null the scene configuration will be use)
  100108. */
  100109. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100110. var _this = this;
  100111. if (configuration === this._imageProcessingConfiguration) {
  100112. return;
  100113. }
  100114. // Detaches observer.
  100115. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100116. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100117. }
  100118. // Pick the scene configuration if needed.
  100119. if (!configuration) {
  100120. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100121. }
  100122. else {
  100123. this._imageProcessingConfiguration = configuration;
  100124. }
  100125. // Attaches observer.
  100126. if (this._imageProcessingConfiguration) {
  100127. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100128. _this._computePrimaryColorFromPerceptualColor();
  100129. _this._markAllSubMeshesAsImageProcessingDirty();
  100130. });
  100131. }
  100132. };
  100133. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100134. /**
  100135. * Gets the image processing configuration used either in this material.
  100136. */
  100137. get: function () {
  100138. return this._imageProcessingConfiguration;
  100139. },
  100140. /**
  100141. * Sets the Default image processing configuration used either in the this material.
  100142. *
  100143. * If sets to null, the scene one is in use.
  100144. */
  100145. set: function (value) {
  100146. this._attachImageProcessingConfiguration(value);
  100147. // Ensure the effect will be rebuilt.
  100148. this._markAllSubMeshesAsTexturesDirty();
  100149. },
  100150. enumerable: true,
  100151. configurable: true
  100152. });
  100153. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100154. /**
  100155. * Gets wether the color curves effect is enabled.
  100156. */
  100157. get: function () {
  100158. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100159. },
  100160. /**
  100161. * Sets wether the color curves effect is enabled.
  100162. */
  100163. set: function (value) {
  100164. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100165. },
  100166. enumerable: true,
  100167. configurable: true
  100168. });
  100169. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100170. /**
  100171. * Gets wether the color grading effect is enabled.
  100172. */
  100173. get: function () {
  100174. return this.imageProcessingConfiguration.colorGradingEnabled;
  100175. },
  100176. /**
  100177. * Gets wether the color grading effect is enabled.
  100178. */
  100179. set: function (value) {
  100180. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100181. },
  100182. enumerable: true,
  100183. configurable: true
  100184. });
  100185. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100186. /**
  100187. * Gets wether tonemapping is enabled or not.
  100188. */
  100189. get: function () {
  100190. return this._imageProcessingConfiguration.toneMappingEnabled;
  100191. },
  100192. /**
  100193. * Sets wether tonemapping is enabled or not
  100194. */
  100195. set: function (value) {
  100196. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100197. },
  100198. enumerable: true,
  100199. configurable: true
  100200. });
  100201. ;
  100202. ;
  100203. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100204. /**
  100205. * The camera exposure used on this material.
  100206. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100207. * This corresponds to a photographic exposure.
  100208. */
  100209. get: function () {
  100210. return this._imageProcessingConfiguration.exposure;
  100211. },
  100212. /**
  100213. * The camera exposure used on this material.
  100214. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100215. * This corresponds to a photographic exposure.
  100216. */
  100217. set: function (value) {
  100218. this._imageProcessingConfiguration.exposure = value;
  100219. },
  100220. enumerable: true,
  100221. configurable: true
  100222. });
  100223. ;
  100224. ;
  100225. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100226. /**
  100227. * Gets The camera contrast used on this material.
  100228. */
  100229. get: function () {
  100230. return this._imageProcessingConfiguration.contrast;
  100231. },
  100232. /**
  100233. * Sets The camera contrast used on this material.
  100234. */
  100235. set: function (value) {
  100236. this._imageProcessingConfiguration.contrast = value;
  100237. },
  100238. enumerable: true,
  100239. configurable: true
  100240. });
  100241. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100242. /**
  100243. * Gets the Color Grading 2D Lookup Texture.
  100244. */
  100245. get: function () {
  100246. return this._imageProcessingConfiguration.colorGradingTexture;
  100247. },
  100248. /**
  100249. * Sets the Color Grading 2D Lookup Texture.
  100250. */
  100251. set: function (value) {
  100252. this.imageProcessingConfiguration.colorGradingTexture = value;
  100253. },
  100254. enumerable: true,
  100255. configurable: true
  100256. });
  100257. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100258. /**
  100259. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100260. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100261. * 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;
  100262. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100263. */
  100264. get: function () {
  100265. return this.imageProcessingConfiguration.colorCurves;
  100266. },
  100267. /**
  100268. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100269. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100270. * 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;
  100271. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100272. */
  100273. set: function (value) {
  100274. this.imageProcessingConfiguration.colorCurves = value;
  100275. },
  100276. enumerable: true,
  100277. configurable: true
  100278. });
  100279. /**
  100280. * The entire material has been created in order to prevent overdraw.
  100281. * @returns false
  100282. */
  100283. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100284. return true;
  100285. };
  100286. /**
  100287. * The entire material has been created in order to prevent overdraw.
  100288. * @returns true if blending is enable
  100289. */
  100290. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100291. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100292. };
  100293. /**
  100294. * Checks wether the material is ready to be rendered for a given mesh.
  100295. * @param mesh The mesh to render
  100296. * @param subMesh The submesh to check against
  100297. * @param useInstances Specify wether or not the material is used with instances
  100298. * @returns true if all the dependencies are ready (Textures, Effects...)
  100299. */
  100300. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100301. var _this = this;
  100302. if (useInstances === void 0) { useInstances = false; }
  100303. if (subMesh.effect && this.isFrozen) {
  100304. if (this._wasPreviouslyReady) {
  100305. return true;
  100306. }
  100307. }
  100308. if (!subMesh._materialDefines) {
  100309. subMesh._materialDefines = new BackgroundMaterialDefines();
  100310. }
  100311. var scene = this.getScene();
  100312. var defines = subMesh._materialDefines;
  100313. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100314. if (defines._renderId === scene.getRenderId()) {
  100315. return true;
  100316. }
  100317. }
  100318. var engine = scene.getEngine();
  100319. // Lights
  100320. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100321. defines._needNormals = true;
  100322. // Textures
  100323. if (defines._areTexturesDirty) {
  100324. defines._needUVs = false;
  100325. if (scene.texturesEnabled) {
  100326. if (scene.getEngine().getCaps().textureLOD) {
  100327. defines.TEXTURELODSUPPORT = true;
  100328. }
  100329. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100330. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100331. return false;
  100332. }
  100333. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100334. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100335. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100336. defines.OPACITYFRESNEL = this._opacityFresnel;
  100337. }
  100338. else {
  100339. defines.DIFFUSE = false;
  100340. defines.DIFFUSEHASALPHA = false;
  100341. defines.GAMMADIFFUSE = false;
  100342. defines.OPACITYFRESNEL = false;
  100343. }
  100344. var reflectionTexture = this._reflectionTexture;
  100345. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100346. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100347. return false;
  100348. }
  100349. defines.REFLECTION = true;
  100350. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100351. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100352. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100353. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100354. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100355. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100356. defines.REFLECTIONBGR = this.switchToBGR;
  100357. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100358. defines.INVERTCUBICMAP = true;
  100359. }
  100360. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100361. switch (reflectionTexture.coordinatesMode) {
  100362. case BABYLON.Texture.EXPLICIT_MODE:
  100363. defines.REFLECTIONMAP_EXPLICIT = true;
  100364. break;
  100365. case BABYLON.Texture.PLANAR_MODE:
  100366. defines.REFLECTIONMAP_PLANAR = true;
  100367. break;
  100368. case BABYLON.Texture.PROJECTION_MODE:
  100369. defines.REFLECTIONMAP_PROJECTION = true;
  100370. break;
  100371. case BABYLON.Texture.SKYBOX_MODE:
  100372. defines.REFLECTIONMAP_SKYBOX = true;
  100373. break;
  100374. case BABYLON.Texture.SPHERICAL_MODE:
  100375. defines.REFLECTIONMAP_SPHERICAL = true;
  100376. break;
  100377. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100378. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100379. break;
  100380. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100381. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100382. break;
  100383. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  100384. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  100385. break;
  100386. case BABYLON.Texture.CUBIC_MODE:
  100387. case BABYLON.Texture.INVCUBIC_MODE:
  100388. default:
  100389. defines.REFLECTIONMAP_CUBIC = true;
  100390. break;
  100391. }
  100392. if (this.reflectionFresnel) {
  100393. defines.REFLECTIONFRESNEL = true;
  100394. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  100395. this._reflectionControls.x = this.reflectionAmount;
  100396. this._reflectionControls.y = this.reflectionReflectance0;
  100397. this._reflectionControls.z = this.reflectionReflectance90;
  100398. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  100399. }
  100400. else {
  100401. defines.REFLECTIONFRESNEL = false;
  100402. defines.REFLECTIONFALLOFF = false;
  100403. }
  100404. }
  100405. else {
  100406. defines.REFLECTION = false;
  100407. defines.REFLECTIONFRESNEL = false;
  100408. defines.REFLECTIONFALLOFF = false;
  100409. defines.REFLECTIONBLUR = false;
  100410. defines.REFLECTIONMAP_3D = false;
  100411. defines.REFLECTIONMAP_SPHERICAL = false;
  100412. defines.REFLECTIONMAP_PLANAR = false;
  100413. defines.REFLECTIONMAP_CUBIC = false;
  100414. defines.REFLECTIONMAP_PROJECTION = false;
  100415. defines.REFLECTIONMAP_SKYBOX = false;
  100416. defines.REFLECTIONMAP_EXPLICIT = false;
  100417. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100418. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100419. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100420. defines.INVERTCUBICMAP = false;
  100421. defines.REFLECTIONMAP_OPPOSITEZ = false;
  100422. defines.LODINREFLECTIONALPHA = false;
  100423. defines.GAMMAREFLECTION = false;
  100424. defines.RGBDREFLECTION = false;
  100425. }
  100426. }
  100427. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  100428. defines.USERGBCOLOR = this._useRGBColor;
  100429. defines.NOISE = this._enableNoise;
  100430. }
  100431. if (defines._areLightsDirty) {
  100432. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  100433. }
  100434. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  100435. if (!this._imageProcessingConfiguration.isReady()) {
  100436. return false;
  100437. }
  100438. this._imageProcessingConfiguration.prepareDefines(defines);
  100439. }
  100440. // Misc.
  100441. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  100442. // Values that need to be evaluated on every frame
  100443. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  100444. // Attribs
  100445. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  100446. if (mesh) {
  100447. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  100448. mesh.createNormals(true);
  100449. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  100450. }
  100451. }
  100452. }
  100453. // Get correct effect
  100454. if (defines.isDirty) {
  100455. defines.markAsProcessed();
  100456. scene.resetCachedMaterial();
  100457. // Fallbacks
  100458. var fallbacks = new BABYLON.EffectFallbacks();
  100459. if (defines.FOG) {
  100460. fallbacks.addFallback(0, "FOG");
  100461. }
  100462. if (defines.POINTSIZE) {
  100463. fallbacks.addFallback(1, "POINTSIZE");
  100464. }
  100465. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  100466. if (defines.NUM_BONE_INFLUENCERS > 0) {
  100467. fallbacks.addCPUSkinningFallback(0, mesh);
  100468. }
  100469. //Attributes
  100470. var attribs = [BABYLON.VertexBuffer.PositionKind];
  100471. if (defines.NORMAL) {
  100472. attribs.push(BABYLON.VertexBuffer.NormalKind);
  100473. }
  100474. if (defines.UV1) {
  100475. attribs.push(BABYLON.VertexBuffer.UVKind);
  100476. }
  100477. if (defines.UV2) {
  100478. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  100479. }
  100480. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  100481. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  100482. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  100483. "vFogInfos", "vFogColor", "pointSize",
  100484. "vClipPlane", "mBones",
  100485. "vPrimaryColor", "vPrimaryColorShadow",
  100486. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  100487. "shadowLevel", "alpha",
  100488. "vBackgroundCenter", "vReflectionControl",
  100489. "vDiffuseInfos", "diffuseMatrix",
  100490. ];
  100491. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  100492. var uniformBuffers = ["Material", "Scene"];
  100493. if (BABYLON.ImageProcessingConfiguration) {
  100494. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  100495. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  100496. }
  100497. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  100498. uniformsNames: uniforms,
  100499. uniformBuffersNames: uniformBuffers,
  100500. samplers: samplers,
  100501. defines: defines,
  100502. maxSimultaneousLights: this._maxSimultaneousLights
  100503. });
  100504. var onCompiled = function (effect) {
  100505. if (_this.onCompiled) {
  100506. _this.onCompiled(effect);
  100507. }
  100508. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  100509. };
  100510. var join = defines.toString();
  100511. subMesh.setEffect(scene.getEngine().createEffect("background", {
  100512. attributes: attribs,
  100513. uniformsNames: uniforms,
  100514. uniformBuffersNames: uniformBuffers,
  100515. samplers: samplers,
  100516. defines: join,
  100517. fallbacks: fallbacks,
  100518. onCompiled: onCompiled,
  100519. onError: this.onError,
  100520. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  100521. }, engine), defines);
  100522. this.buildUniformLayout();
  100523. }
  100524. if (!subMesh.effect || !subMesh.effect.isReady()) {
  100525. return false;
  100526. }
  100527. defines._renderId = scene.getRenderId();
  100528. this._wasPreviouslyReady = true;
  100529. return true;
  100530. };
  100531. /**
  100532. * Compute the primary color according to the chosen perceptual color.
  100533. */
  100534. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  100535. if (!this.__perceptualColor) {
  100536. return;
  100537. }
  100538. this._primaryColor.copyFrom(this.__perceptualColor);
  100539. // Revert gamma space.
  100540. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  100541. // Revert image processing configuration.
  100542. if (this._imageProcessingConfiguration) {
  100543. // Revert Exposure.
  100544. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  100545. }
  100546. this._computePrimaryColors();
  100547. };
  100548. /**
  100549. * Compute the highlights and shadow colors according to their chosen levels.
  100550. */
  100551. BackgroundMaterial.prototype._computePrimaryColors = function () {
  100552. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  100553. return;
  100554. }
  100555. // Find the highlight color based on the configuration.
  100556. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  100557. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  100558. // Find the shadow color based on the configuration.
  100559. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  100560. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  100561. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  100562. };
  100563. /**
  100564. * Build the uniform buffer used in the material.
  100565. */
  100566. BackgroundMaterial.prototype.buildUniformLayout = function () {
  100567. // Order is important !
  100568. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  100569. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  100570. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  100571. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  100572. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  100573. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  100574. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  100575. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  100576. this._uniformBuffer.addUniform("pointSize", 1);
  100577. this._uniformBuffer.addUniform("shadowLevel", 1);
  100578. this._uniformBuffer.addUniform("alpha", 1);
  100579. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  100580. this._uniformBuffer.addUniform("vReflectionControl", 4);
  100581. this._uniformBuffer.create();
  100582. };
  100583. /**
  100584. * Unbind the material.
  100585. */
  100586. BackgroundMaterial.prototype.unbind = function () {
  100587. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  100588. this._uniformBuffer.setTexture("diffuseSampler", null);
  100589. }
  100590. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  100591. this._uniformBuffer.setTexture("reflectionSampler", null);
  100592. }
  100593. _super.prototype.unbind.call(this);
  100594. };
  100595. /**
  100596. * Bind only the world matrix to the material.
  100597. * @param world The world matrix to bind.
  100598. */
  100599. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  100600. this._activeEffect.setMatrix("world", world);
  100601. };
  100602. /**
  100603. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  100604. * @param world The world matrix to bind.
  100605. * @param subMesh The submesh to bind for.
  100606. */
  100607. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  100608. var scene = this.getScene();
  100609. var defines = subMesh._materialDefines;
  100610. if (!defines) {
  100611. return;
  100612. }
  100613. var effect = subMesh.effect;
  100614. if (!effect) {
  100615. return;
  100616. }
  100617. this._activeEffect = effect;
  100618. // Matrices
  100619. this.bindOnlyWorldMatrix(world);
  100620. // Bones
  100621. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  100622. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  100623. if (mustRebind) {
  100624. this._uniformBuffer.bindToEffect(effect, "Material");
  100625. this.bindViewProjection(effect);
  100626. var reflectionTexture = this._reflectionTexture;
  100627. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  100628. // Texture uniforms
  100629. if (scene.texturesEnabled) {
  100630. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100631. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  100632. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  100633. }
  100634. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100635. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  100636. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  100637. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  100638. }
  100639. }
  100640. if (this.shadowLevel > 0) {
  100641. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  100642. }
  100643. this._uniformBuffer.updateFloat("alpha", this.alpha);
  100644. // Point size
  100645. if (this.pointsCloud) {
  100646. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  100647. }
  100648. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  100649. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  100650. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  100651. }
  100652. else {
  100653. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  100654. }
  100655. }
  100656. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  100657. // Textures
  100658. if (scene.texturesEnabled) {
  100659. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100660. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  100661. }
  100662. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100663. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  100664. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100665. }
  100666. else if (!defines.REFLECTIONBLUR) {
  100667. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  100668. }
  100669. else {
  100670. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  100671. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  100672. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  100673. }
  100674. if (defines.REFLECTIONFRESNEL) {
  100675. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  100676. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  100677. }
  100678. }
  100679. }
  100680. // Clip plane
  100681. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  100682. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  100683. }
  100684. if (mustRebind || !this.isFrozen) {
  100685. if (scene.lightsEnabled) {
  100686. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  100687. }
  100688. // View
  100689. this.bindView(effect);
  100690. // Fog
  100691. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  100692. // image processing
  100693. if (this._imageProcessingConfiguration) {
  100694. this._imageProcessingConfiguration.bind(this._activeEffect);
  100695. }
  100696. }
  100697. this._uniformBuffer.update();
  100698. this._afterBind(mesh, this._activeEffect);
  100699. };
  100700. /**
  100701. * Dispose the material.
  100702. * @param forceDisposeEffect Force disposal of the associated effect.
  100703. * @param forceDisposeTextures Force disposal of the associated textures.
  100704. */
  100705. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  100706. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  100707. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  100708. if (forceDisposeTextures) {
  100709. if (this.diffuseTexture) {
  100710. this.diffuseTexture.dispose();
  100711. }
  100712. if (this.reflectionTexture) {
  100713. this.reflectionTexture.dispose();
  100714. }
  100715. }
  100716. this._renderTargets.dispose();
  100717. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100718. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100719. }
  100720. _super.prototype.dispose.call(this, forceDisposeEffect);
  100721. };
  100722. /**
  100723. * Clones the material.
  100724. * @param name The cloned name.
  100725. * @returns The cloned material.
  100726. */
  100727. BackgroundMaterial.prototype.clone = function (name) {
  100728. var _this = this;
  100729. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  100730. };
  100731. /**
  100732. * Serializes the current material to its JSON representation.
  100733. * @returns The JSON representation.
  100734. */
  100735. BackgroundMaterial.prototype.serialize = function () {
  100736. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  100737. serializationObject.customType = "BABYLON.BackgroundMaterial";
  100738. return serializationObject;
  100739. };
  100740. /**
  100741. * Gets the class name of the material
  100742. * @returns "BackgroundMaterial"
  100743. */
  100744. BackgroundMaterial.prototype.getClassName = function () {
  100745. return "BackgroundMaterial";
  100746. };
  100747. /**
  100748. * Parse a JSON input to create back a background material.
  100749. * @param source The JSON data to parse
  100750. * @param scene The scene to create the parsed material in
  100751. * @param rootUrl The root url of the assets the material depends upon
  100752. * @returns the instantiated BackgroundMaterial.
  100753. */
  100754. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  100755. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  100756. };
  100757. /**
  100758. * Standard reflectance value at parallel view angle.
  100759. */
  100760. BackgroundMaterial.StandardReflectance0 = 0.05;
  100761. /**
  100762. * Standard reflectance value at grazing angle.
  100763. */
  100764. BackgroundMaterial.StandardReflectance90 = 0.5;
  100765. __decorate([
  100766. BABYLON.serializeAsColor3()
  100767. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  100768. __decorate([
  100769. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100770. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  100771. __decorate([
  100772. BABYLON.serializeAsColor3()
  100773. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  100774. __decorate([
  100775. BABYLON.serialize()
  100776. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  100777. __decorate([
  100778. BABYLON.serialize()
  100779. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  100780. __decorate([
  100781. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  100782. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  100783. __decorate([
  100784. BABYLON.serializeAsTexture()
  100785. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  100786. __decorate([
  100787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100788. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  100789. __decorate([
  100790. BABYLON.serialize()
  100791. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  100792. __decorate([
  100793. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100794. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  100795. __decorate([
  100796. BABYLON.serializeAsTexture()
  100797. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  100798. __decorate([
  100799. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100800. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  100801. __decorate([
  100802. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100803. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  100804. __decorate([
  100805. BABYLON.serialize()
  100806. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  100807. __decorate([
  100808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100809. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  100810. __decorate([
  100811. BABYLON.serializeAsVector3()
  100812. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  100813. __decorate([
  100814. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100815. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  100816. __decorate([
  100817. BABYLON.serialize()
  100818. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  100819. __decorate([
  100820. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100821. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  100822. __decorate([
  100823. BABYLON.serialize()
  100824. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  100825. __decorate([
  100826. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100827. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  100828. __decorate([
  100829. BABYLON.serialize()
  100830. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  100831. __decorate([
  100832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100833. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  100834. __decorate([
  100835. BABYLON.serialize()
  100836. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  100837. __decorate([
  100838. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100839. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  100840. __decorate([
  100841. BABYLON.serialize()
  100842. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  100843. __decorate([
  100844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100845. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  100846. __decorate([
  100847. BABYLON.serialize()
  100848. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  100849. __decorate([
  100850. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100851. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  100852. __decorate([
  100853. BABYLON.serialize()
  100854. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  100855. __decorate([
  100856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100857. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  100858. __decorate([
  100859. BABYLON.serialize()
  100860. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  100861. __decorate([
  100862. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100863. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  100864. __decorate([
  100865. BABYLON.serialize()
  100866. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  100867. __decorate([
  100868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  100869. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  100870. __decorate([
  100871. BABYLON.serializeAsImageProcessingConfiguration()
  100872. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  100873. return BackgroundMaterial;
  100874. }(BABYLON.PushMaterial));
  100875. BABYLON.BackgroundMaterial = BackgroundMaterial;
  100876. })(BABYLON || (BABYLON = {}));
  100877. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  100878. var __assign = (this && this.__assign) || Object.assign || function(t) {
  100879. for (var s, i = 1, n = arguments.length; i < n; i++) {
  100880. s = arguments[i];
  100881. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  100882. t[p] = s[p];
  100883. }
  100884. return t;
  100885. };
  100886. var BABYLON;
  100887. (function (BABYLON) {
  100888. /**
  100889. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  100890. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  100891. * It also helps with the default setup of your imageProcessing configuration.
  100892. */
  100893. var EnvironmentHelper = /** @class */ (function () {
  100894. /**
  100895. * constructor
  100896. * @param options
  100897. * @param scene The scene to add the material to
  100898. */
  100899. function EnvironmentHelper(options, scene) {
  100900. var _this = this;
  100901. this._errorHandler = function (message, exception) {
  100902. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  100903. };
  100904. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  100905. this._scene = scene;
  100906. this.onErrorObservable = new BABYLON.Observable();
  100907. this._setupBackground();
  100908. this._setupImageProcessing();
  100909. }
  100910. /**
  100911. * Creates the default options for the helper.
  100912. */
  100913. EnvironmentHelper._getDefaultOptions = function () {
  100914. return {
  100915. createGround: true,
  100916. groundSize: 15,
  100917. groundTexture: this._groundTextureCDNUrl,
  100918. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100919. groundOpacity: 0.9,
  100920. enableGroundShadow: true,
  100921. groundShadowLevel: 0.5,
  100922. enableGroundMirror: false,
  100923. groundMirrorSizeRatio: 0.3,
  100924. groundMirrorBlurKernel: 64,
  100925. groundMirrorAmount: 1,
  100926. groundMirrorFresnelWeight: 1,
  100927. groundMirrorFallOffDistance: 0,
  100928. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  100929. groundYBias: 0.00001,
  100930. createSkybox: true,
  100931. skyboxSize: 20,
  100932. skyboxTexture: this._skyboxTextureCDNUrl,
  100933. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  100934. backgroundYRotation: 0,
  100935. sizeAuto: true,
  100936. rootPosition: BABYLON.Vector3.Zero(),
  100937. setupImageProcessing: true,
  100938. environmentTexture: this._environmentTextureCDNUrl,
  100939. cameraExposure: 0.8,
  100940. cameraContrast: 1.2,
  100941. toneMappingEnabled: true,
  100942. };
  100943. };
  100944. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  100945. /**
  100946. * Gets the root mesh created by the helper.
  100947. */
  100948. get: function () {
  100949. return this._rootMesh;
  100950. },
  100951. enumerable: true,
  100952. configurable: true
  100953. });
  100954. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  100955. /**
  100956. * Gets the skybox created by the helper.
  100957. */
  100958. get: function () {
  100959. return this._skybox;
  100960. },
  100961. enumerable: true,
  100962. configurable: true
  100963. });
  100964. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  100965. /**
  100966. * Gets the skybox texture created by the helper.
  100967. */
  100968. get: function () {
  100969. return this._skyboxTexture;
  100970. },
  100971. enumerable: true,
  100972. configurable: true
  100973. });
  100974. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  100975. /**
  100976. * Gets the skybox material created by the helper.
  100977. */
  100978. get: function () {
  100979. return this._skyboxMaterial;
  100980. },
  100981. enumerable: true,
  100982. configurable: true
  100983. });
  100984. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  100985. /**
  100986. * Gets the ground mesh created by the helper.
  100987. */
  100988. get: function () {
  100989. return this._ground;
  100990. },
  100991. enumerable: true,
  100992. configurable: true
  100993. });
  100994. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  100995. /**
  100996. * Gets the ground texture created by the helper.
  100997. */
  100998. get: function () {
  100999. return this._groundTexture;
  101000. },
  101001. enumerable: true,
  101002. configurable: true
  101003. });
  101004. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101005. /**
  101006. * Gets the ground mirror created by the helper.
  101007. */
  101008. get: function () {
  101009. return this._groundMirror;
  101010. },
  101011. enumerable: true,
  101012. configurable: true
  101013. });
  101014. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101015. /**
  101016. * Gets the ground mirror render list to helps pushing the meshes
  101017. * you wish in the ground reflection.
  101018. */
  101019. get: function () {
  101020. if (this._groundMirror) {
  101021. return this._groundMirror.renderList;
  101022. }
  101023. return null;
  101024. },
  101025. enumerable: true,
  101026. configurable: true
  101027. });
  101028. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101029. /**
  101030. * Gets the ground material created by the helper.
  101031. */
  101032. get: function () {
  101033. return this._groundMaterial;
  101034. },
  101035. enumerable: true,
  101036. configurable: true
  101037. });
  101038. /**
  101039. * Updates the background according to the new options
  101040. * @param options
  101041. */
  101042. EnvironmentHelper.prototype.updateOptions = function (options) {
  101043. var newOptions = __assign({}, this._options, options);
  101044. if (this._ground && !newOptions.createGround) {
  101045. this._ground.dispose();
  101046. this._ground = null;
  101047. }
  101048. if (this._groundMaterial && !newOptions.createGround) {
  101049. this._groundMaterial.dispose();
  101050. this._groundMaterial = null;
  101051. }
  101052. if (this._groundTexture) {
  101053. if (this._options.groundTexture != newOptions.groundTexture) {
  101054. this._groundTexture.dispose();
  101055. this._groundTexture = null;
  101056. }
  101057. }
  101058. if (this._skybox && !newOptions.createSkybox) {
  101059. this._skybox.dispose();
  101060. this._skybox = null;
  101061. }
  101062. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101063. this._skyboxMaterial.dispose();
  101064. this._skyboxMaterial = null;
  101065. }
  101066. if (this._skyboxTexture) {
  101067. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101068. this._skyboxTexture.dispose();
  101069. this._skyboxTexture = null;
  101070. }
  101071. }
  101072. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101073. this._groundMirror.dispose();
  101074. this._groundMirror = null;
  101075. }
  101076. if (this._scene.environmentTexture) {
  101077. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101078. this._scene.environmentTexture.dispose();
  101079. }
  101080. }
  101081. this._options = newOptions;
  101082. this._setupBackground();
  101083. this._setupImageProcessing();
  101084. };
  101085. /**
  101086. * Sets the primary color of all the available elements.
  101087. * @param color the main color to affect to the ground and the background
  101088. */
  101089. EnvironmentHelper.prototype.setMainColor = function (color) {
  101090. if (this.groundMaterial) {
  101091. this.groundMaterial.primaryColor = color;
  101092. }
  101093. if (this.skyboxMaterial) {
  101094. this.skyboxMaterial.primaryColor = color;
  101095. }
  101096. if (this.groundMirror) {
  101097. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101098. }
  101099. };
  101100. /**
  101101. * Setup the image processing according to the specified options.
  101102. */
  101103. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101104. if (this._options.setupImageProcessing) {
  101105. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101106. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101107. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101108. this._setupEnvironmentTexture();
  101109. }
  101110. };
  101111. /**
  101112. * Setup the environment texture according to the specified options.
  101113. */
  101114. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101115. if (this._scene.environmentTexture) {
  101116. return;
  101117. }
  101118. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101119. this._scene.environmentTexture = this._options.environmentTexture;
  101120. return;
  101121. }
  101122. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101123. this._scene.environmentTexture = environmentTexture;
  101124. };
  101125. /**
  101126. * Setup the background according to the specified options.
  101127. */
  101128. EnvironmentHelper.prototype._setupBackground = function () {
  101129. if (!this._rootMesh) {
  101130. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101131. }
  101132. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101133. var sceneSize = this._getSceneSize();
  101134. if (this._options.createGround) {
  101135. this._setupGround(sceneSize);
  101136. this._setupGroundMaterial();
  101137. this._setupGroundDiffuseTexture();
  101138. if (this._options.enableGroundMirror) {
  101139. this._setupGroundMirrorTexture(sceneSize);
  101140. }
  101141. this._setupMirrorInGroundMaterial();
  101142. }
  101143. if (this._options.createSkybox) {
  101144. this._setupSkybox(sceneSize);
  101145. this._setupSkyboxMaterial();
  101146. this._setupSkyboxReflectionTexture();
  101147. }
  101148. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101149. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101150. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101151. };
  101152. /**
  101153. * Get the scene sizes according to the setup.
  101154. */
  101155. EnvironmentHelper.prototype._getSceneSize = function () {
  101156. var _this = this;
  101157. var groundSize = this._options.groundSize;
  101158. var skyboxSize = this._options.skyboxSize;
  101159. var rootPosition = this._options.rootPosition;
  101160. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101161. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101162. }
  101163. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101164. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101165. });
  101166. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101167. if (this._options.sizeAuto) {
  101168. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101169. this._scene.activeCamera.upperRadiusLimit) {
  101170. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101171. skyboxSize = groundSize;
  101172. }
  101173. var sceneDiagonalLenght = sceneDiagonal.length();
  101174. if (sceneDiagonalLenght > groundSize) {
  101175. groundSize = sceneDiagonalLenght * 2;
  101176. skyboxSize = groundSize;
  101177. }
  101178. // 10 % bigger.
  101179. groundSize *= 1.1;
  101180. skyboxSize *= 1.5;
  101181. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101182. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101183. }
  101184. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101185. };
  101186. /**
  101187. * Setup the ground according to the specified options.
  101188. */
  101189. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101190. var _this = this;
  101191. if (!this._ground || this._ground.isDisposed()) {
  101192. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101193. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101194. this._ground.parent = this._rootMesh;
  101195. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101196. }
  101197. this._ground.receiveShadows = this._options.enableGroundShadow;
  101198. };
  101199. /**
  101200. * Setup the ground material according to the specified options.
  101201. */
  101202. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101203. if (!this._groundMaterial) {
  101204. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101205. }
  101206. this._groundMaterial.alpha = this._options.groundOpacity;
  101207. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101208. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101209. this._groundMaterial.primaryColor = this._options.groundColor;
  101210. this._groundMaterial.useRGBColor = false;
  101211. this._groundMaterial.enableNoise = true;
  101212. if (this._ground) {
  101213. this._ground.material = this._groundMaterial;
  101214. }
  101215. };
  101216. /**
  101217. * Setup the ground diffuse texture according to the specified options.
  101218. */
  101219. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101220. if (!this._groundMaterial) {
  101221. return;
  101222. }
  101223. if (this._groundTexture) {
  101224. return;
  101225. }
  101226. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101227. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101228. return;
  101229. }
  101230. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101231. diffuseTexture.gammaSpace = false;
  101232. diffuseTexture.hasAlpha = true;
  101233. this._groundMaterial.diffuseTexture = diffuseTexture;
  101234. };
  101235. /**
  101236. * Setup the ground mirror texture according to the specified options.
  101237. */
  101238. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101239. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101240. if (!this._groundMirror) {
  101241. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101242. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101243. this._groundMirror.anisotropicFilteringLevel = 1;
  101244. this._groundMirror.wrapU = wrapping;
  101245. this._groundMirror.wrapV = wrapping;
  101246. this._groundMirror.gammaSpace = false;
  101247. if (this._groundMirror.renderList) {
  101248. for (var i = 0; i < this._scene.meshes.length; i++) {
  101249. var mesh = this._scene.meshes[i];
  101250. if (mesh !== this._ground &&
  101251. mesh !== this._skybox &&
  101252. mesh !== this._rootMesh) {
  101253. this._groundMirror.renderList.push(mesh);
  101254. }
  101255. }
  101256. }
  101257. }
  101258. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101259. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101260. };
  101261. /**
  101262. * Setup the ground to receive the mirror texture.
  101263. */
  101264. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101265. if (this._groundMaterial) {
  101266. this._groundMaterial.reflectionTexture = this._groundMirror;
  101267. this._groundMaterial.reflectionFresnel = true;
  101268. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101269. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101270. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101271. }
  101272. };
  101273. /**
  101274. * Setup the skybox according to the specified options.
  101275. */
  101276. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101277. var _this = this;
  101278. if (!this._skybox || this._skybox.isDisposed()) {
  101279. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101280. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101281. }
  101282. this._skybox.parent = this._rootMesh;
  101283. };
  101284. /**
  101285. * Setup the skybox material according to the specified options.
  101286. */
  101287. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101288. if (!this._skybox) {
  101289. return;
  101290. }
  101291. if (!this._skyboxMaterial) {
  101292. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101293. }
  101294. this._skyboxMaterial.useRGBColor = false;
  101295. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101296. this._skyboxMaterial.enableNoise = true;
  101297. this._skybox.material = this._skyboxMaterial;
  101298. };
  101299. /**
  101300. * Setup the skybox reflection texture according to the specified options.
  101301. */
  101302. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101303. if (!this._skyboxMaterial) {
  101304. return;
  101305. }
  101306. if (this._skyboxTexture) {
  101307. return;
  101308. }
  101309. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101310. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101311. return;
  101312. }
  101313. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101314. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101315. this._skyboxTexture.gammaSpace = false;
  101316. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101317. };
  101318. /**
  101319. * Dispose all the elements created by the Helper.
  101320. */
  101321. EnvironmentHelper.prototype.dispose = function () {
  101322. if (this._groundMaterial) {
  101323. this._groundMaterial.dispose(true, true);
  101324. }
  101325. if (this._skyboxMaterial) {
  101326. this._skyboxMaterial.dispose(true, true);
  101327. }
  101328. this._rootMesh.dispose(false);
  101329. };
  101330. /**
  101331. * Default ground texture URL.
  101332. */
  101333. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101334. /**
  101335. * Default skybox texture URL.
  101336. */
  101337. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101338. /**
  101339. * Default environment texture URL.
  101340. */
  101341. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101342. return EnvironmentHelper;
  101343. }());
  101344. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101345. })(BABYLON || (BABYLON = {}));
  101346. //# sourceMappingURL=babylon.environmentHelper.js.map
  101347. var BABYLON;
  101348. (function (BABYLON) {
  101349. /**
  101350. * This class is made for on one-liner static method to help creating particle systems.
  101351. */
  101352. var ParticleHelper = /** @class */ (function () {
  101353. function ParticleHelper() {
  101354. }
  101355. /**
  101356. * This is the main static method (one-liner) of this helper to create different particle systems.
  101357. * @param type This string represents the type to the particle system to create
  101358. * @param emitter The object where the particle system will start to emit from.
  101359. * @param scene The scene where the particle system should live.
  101360. * @param gpu If the system will use gpu.
  101361. * @returns the ParticleSystem created.
  101362. */
  101363. ParticleHelper.CreateAsync = function (type, emitter, scene, gpu) {
  101364. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  101365. if (gpu === void 0) { gpu = false; }
  101366. return new Promise(function (resolve, reject) {
  101367. if (!scene) {
  101368. scene = BABYLON.Engine.LastCreatedScene;
  101369. ;
  101370. }
  101371. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  101372. return reject("Particle system with GPU is not supported.");
  101373. }
  101374. BABYLON.Tools.LoadFile(ParticleHelper._baseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  101375. var newData = JSON.parse(data.toString());
  101376. return resolve(ParticleHelper.CreateSystem(newData, scene, emitter));
  101377. }, undefined, undefined, undefined, function (req, exception) {
  101378. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  101379. });
  101380. });
  101381. };
  101382. /**
  101383. * Static function used to create a new particle system from a IParticleSystemData
  101384. * @param data defines the source data
  101385. * @param scene defines the hosting scene
  101386. * @param emitter defines the particle emitter
  101387. * @returns a new ParticleSystem based on referenced data
  101388. */
  101389. ParticleHelper.CreateSystem = function (data, scene, emitter) {
  101390. // Create a particle system
  101391. var system = new BABYLON.ParticleSystem(data.type, data.capacity, scene);
  101392. // Where the particles come from
  101393. system.emitter = emitter; // the starting object, the emitter
  101394. ParticleHelper.UpdateSystem(system, data, scene);
  101395. return system;
  101396. };
  101397. /**
  101398. * Static function used to update a particle system from a IParticleSystemData
  101399. * @param system defines the particle system to update
  101400. * @param data defines the source data
  101401. * @param scene defines the hosting scene
  101402. */
  101403. ParticleHelper.UpdateSystem = function (system, data, scene) {
  101404. // Texture of each particle
  101405. if (data.textureFile) {
  101406. system.particleTexture = new BABYLON.Texture(ParticleHelper._baseAssetsUrl + "/textures/" + data.textureFile, scene);
  101407. }
  101408. // Colors of all particles
  101409. system.color1 = new BABYLON.Color4(data.color1.r, data.color1.g, data.color1.b, data.color1.a);
  101410. system.color2 = new BABYLON.Color4(data.color2.r, data.color2.g, data.color2.b, data.color2.a);
  101411. system.colorDead = new BABYLON.Color4(data.colorDead.r, data.colorDead.g, data.colorDead.b, data.colorDead.a);
  101412. // Size of each particle (random between...
  101413. system.minSize = data.minSize;
  101414. system.maxSize = data.maxSize;
  101415. system.minScaleX = data.minScaleX;
  101416. system.maxScaleX = data.maxScaleX;
  101417. system.minScaleY = data.minScaleY;
  101418. system.maxScaleY = data.maxScaleY;
  101419. // Life time of each particle (random between...
  101420. system.minLifeTime = data.minLifeTime;
  101421. system.maxLifeTime = data.maxLifeTime;
  101422. // Emission rate
  101423. system.emitRate = data.emitRate;
  101424. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101425. system.blendMode = data.blendMode;
  101426. // Set the gravity of all particles
  101427. system.gravity = new BABYLON.Vector3(data.gravity.x, data.gravity.y, data.gravity.z);
  101428. // Angular speed, in radians
  101429. system.minAngularSpeed = data.minAngularSpeed;
  101430. system.maxAngularSpeed = data.maxAngularSpeed;
  101431. // Speed
  101432. system.minEmitPower = data.minEmitPower;
  101433. system.maxEmitPower = data.maxEmitPower;
  101434. system.updateSpeed = data.updateSpeed;
  101435. switch (data.emitterType) {
  101436. case "box":
  101437. if (!data.direction1 || !data.direction2) {
  101438. throw new Error("Directions are missing in this particle system.");
  101439. }
  101440. if (!data.minEmitBox || !data.maxEmitBox) {
  101441. throw new Error("EmitBox is missing in this particle system.");
  101442. }
  101443. system.createBoxEmitter(new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z), new BABYLON.Vector3(data.minEmitBox.x, data.minEmitBox.y, data.minEmitBox.z), new BABYLON.Vector3(data.maxEmitBox.x, data.maxEmitBox.y, data.maxEmitBox.z));
  101444. break;
  101445. case "sphere":
  101446. system.createSphereEmitter(data.radius);
  101447. break;
  101448. case "directed_sphere":
  101449. if (!data.direction1 || !data.direction2) {
  101450. throw new Error("Directions are missing in this particle system.");
  101451. }
  101452. system.createDirectedSphereEmitter(data.radius, new BABYLON.Vector3(data.direction1.x, data.direction1.y, data.direction1.z), new BABYLON.Vector3(data.direction2.x, data.direction2.y, data.direction2.z));
  101453. break;
  101454. case "cone":
  101455. system.createConeEmitter(data.radius, data.angle);
  101456. break;
  101457. default:
  101458. break;
  101459. }
  101460. };
  101461. /**
  101462. * Static function used to export a particle system to a IParticleSystemData variable.
  101463. * Please note that texture file name is not exported and must be added manually
  101464. * @param system defines the particle system to export
  101465. */
  101466. ParticleHelper.ExportSystem = function (system) {
  101467. var outData = {};
  101468. // Colors of all particles
  101469. outData.color1 = { r: system.color1.r, g: system.color1.g, b: system.color1.b, a: system.color1.a };
  101470. outData.color2 = { r: system.color2.r, g: system.color2.g, b: system.color2.b, a: system.color2.a };
  101471. outData.colorDead = { r: system.colorDead.r, g: system.colorDead.g, b: system.colorDead.b, a: system.colorDead.a };
  101472. // Size of each particle (random between...
  101473. outData.minSize = system.minSize;
  101474. outData.maxSize = system.maxSize;
  101475. outData.minScaleX = system.minScaleX;
  101476. outData.maxScaleX = system.maxScaleX;
  101477. outData.minScaleY = system.minScaleY;
  101478. outData.maxScaleY = system.maxScaleY;
  101479. // Life time of each particle (random between...
  101480. outData.minLifeTime = system.minLifeTime;
  101481. outData.maxLifeTime = system.maxLifeTime;
  101482. // Emission rate
  101483. outData.emitRate = system.emitRate;
  101484. // Blend mode : BLENDMODE_ONEONE, or BLENDMODE_STANDARD
  101485. outData.blendMode = system.blendMode;
  101486. // Set the gravity of all particles
  101487. outData.gravity = { x: system.gravity.x, y: system.gravity.y, z: system.gravity.z };
  101488. // Angular speed, in radians
  101489. outData.minAngularSpeed = system.minAngularSpeed;
  101490. outData.maxAngularSpeed = system.maxAngularSpeed;
  101491. // Speed
  101492. outData.minEmitPower = system.minEmitPower;
  101493. outData.maxEmitPower = system.maxEmitPower;
  101494. outData.updateSpeed = system.updateSpeed;
  101495. switch (system.particleEmitterType.getClassName()) {
  101496. case "BoxEmitter":
  101497. outData.emitterType = "box";
  101498. outData.direction1 = { x: system.direction1.x, y: system.direction1.y, z: system.direction1.z };
  101499. outData.direction2 = { x: system.direction2.x, y: system.direction2.y, z: system.direction2.z };
  101500. outData.minEmitBox = { x: system.minEmitBox.x, y: system.minEmitBox.y, z: system.minEmitBox.z };
  101501. outData.maxEmitBox = { x: system.maxEmitBox.x, y: system.maxEmitBox.y, z: system.maxEmitBox.z };
  101502. break;
  101503. case "SphereParticleEmitter":
  101504. outData.emitterType = "sphere";
  101505. outData.radius = system.particleEmitterType.radius;
  101506. break;
  101507. case "SphereDirectedParticleEmitter":
  101508. outData.emitterType = "directed_sphere";
  101509. var sphereDirectedParticleEmitter = system.particleEmitterType;
  101510. outData.radius = sphereDirectedParticleEmitter.radius;
  101511. outData.direction1 = { x: sphereDirectedParticleEmitter.direction1.x, y: sphereDirectedParticleEmitter.direction1.y, z: sphereDirectedParticleEmitter.direction1.z };
  101512. outData.direction2 = { x: sphereDirectedParticleEmitter.direction2.x, y: sphereDirectedParticleEmitter.direction2.y, z: sphereDirectedParticleEmitter.direction2.z };
  101513. break;
  101514. case "ConeEmitter":
  101515. outData.emitterType = "cone";
  101516. outData.radius = system.particleEmitterType.radius;
  101517. outData.angle = system.particleEmitterType.angle;
  101518. break;
  101519. default:
  101520. break;
  101521. }
  101522. return outData;
  101523. };
  101524. /**
  101525. * Base Assets URL.
  101526. */
  101527. ParticleHelper._baseAssetsUrl = "https://assets.babylonjs.com/particles";
  101528. return ParticleHelper;
  101529. }());
  101530. BABYLON.ParticleHelper = ParticleHelper;
  101531. })(BABYLON || (BABYLON = {}));
  101532. //# sourceMappingURL=babylon.particleHelper.js.map
  101533. var BABYLON;
  101534. (function (BABYLON) {
  101535. /**
  101536. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  101537. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  101538. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  101539. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101540. */
  101541. var VideoDome = /** @class */ (function (_super) {
  101542. __extends(VideoDome, _super);
  101543. /**
  101544. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  101545. * @param name Element's name, child elements will append suffixes for their own names.
  101546. * @param urlsOrVideo defines the url(s) or the video element to use
  101547. * @param options An object containing optional or exposed sub element properties
  101548. */
  101549. function VideoDome(name, urlsOrVideo, options, scene) {
  101550. var _this = _super.call(this, name, scene) || this;
  101551. _this._useDirectMapping = false;
  101552. // set defaults and manage values
  101553. name = name || "videoDome";
  101554. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101555. options.clickToPlay = Boolean(options.clickToPlay);
  101556. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  101557. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  101558. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101559. if (options.useDirectMapping === undefined) {
  101560. _this._useDirectMapping = true;
  101561. }
  101562. else {
  101563. _this._useDirectMapping = options.useDirectMapping;
  101564. }
  101565. // create
  101566. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  101567. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101568. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  101569. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101570. // configure material
  101571. material.useEquirectangularFOV = true;
  101572. material.fovMultiplier = 1.0;
  101573. material.opacityFresnel = false;
  101574. if (_this._useDirectMapping) {
  101575. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101576. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101577. material.diffuseTexture = texture;
  101578. }
  101579. else {
  101580. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101581. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101582. material.reflectionTexture = texture;
  101583. }
  101584. // configure mesh
  101585. _this._mesh.material = material;
  101586. _this._mesh.parent = _this;
  101587. // optional configuration
  101588. if (options.clickToPlay) {
  101589. scene.onPointerUp = function () {
  101590. _this._videoTexture.video.play();
  101591. };
  101592. }
  101593. return _this;
  101594. }
  101595. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  101596. /**
  101597. * Gets the video texture being displayed on the sphere
  101598. */
  101599. get: function () {
  101600. return this._videoTexture;
  101601. },
  101602. enumerable: true,
  101603. configurable: true
  101604. });
  101605. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  101606. /**
  101607. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101608. * Also see the options.resolution property.
  101609. */
  101610. get: function () {
  101611. return this._material.fovMultiplier;
  101612. },
  101613. set: function (value) {
  101614. this._material.fovMultiplier = value;
  101615. },
  101616. enumerable: true,
  101617. configurable: true
  101618. });
  101619. /**
  101620. * Releases resources associated with this node.
  101621. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101622. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101623. */
  101624. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101625. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101626. this._videoTexture.dispose();
  101627. this._mesh.dispose();
  101628. this._material.dispose();
  101629. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101630. };
  101631. return VideoDome;
  101632. }(BABYLON.Node));
  101633. BABYLON.VideoDome = VideoDome;
  101634. })(BABYLON || (BABYLON = {}));
  101635. //# sourceMappingURL=babylon.videoDome.js.map
  101636. var BABYLON;
  101637. (function (BABYLON) {
  101638. /**
  101639. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  101640. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  101641. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  101642. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  101643. */
  101644. var PhotoDome = /** @class */ (function (_super) {
  101645. __extends(PhotoDome, _super);
  101646. /**
  101647. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  101648. * @param name Element's name, child elements will append suffixes for their own names.
  101649. * @param urlsOfPhoto define the url of the photo to display
  101650. * @param options An object containing optional or exposed sub element properties
  101651. */
  101652. function PhotoDome(name, urlOfPhoto, options, scene) {
  101653. var _this = _super.call(this, name, scene) || this;
  101654. _this._useDirectMapping = false;
  101655. // set defaults and manage values
  101656. name = name || "photoDome";
  101657. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  101658. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  101659. if (options.useDirectMapping === undefined) {
  101660. _this._useDirectMapping = true;
  101661. }
  101662. else {
  101663. _this._useDirectMapping = options.useDirectMapping;
  101664. }
  101665. // create
  101666. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  101667. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  101668. // configure material
  101669. material.opacityFresnel = false;
  101670. material.useEquirectangularFOV = true;
  101671. material.fovMultiplier = 1.0;
  101672. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  101673. // configure mesh
  101674. _this._mesh.material = material;
  101675. _this._mesh.parent = _this;
  101676. return _this;
  101677. }
  101678. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  101679. /**
  101680. * Gets or sets the texture being displayed on the sphere
  101681. */
  101682. get: function () {
  101683. return this._photoTexture;
  101684. },
  101685. set: function (value) {
  101686. if (this._photoTexture === value) {
  101687. return;
  101688. }
  101689. this._photoTexture = value;
  101690. if (this._useDirectMapping) {
  101691. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101692. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101693. this._material.diffuseTexture = this._photoTexture;
  101694. }
  101695. else {
  101696. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  101697. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101698. this._material.reflectionTexture = this._photoTexture;
  101699. }
  101700. },
  101701. enumerable: true,
  101702. configurable: true
  101703. });
  101704. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  101705. /**
  101706. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  101707. * Also see the options.resolution property.
  101708. */
  101709. get: function () {
  101710. return this._material.fovMultiplier;
  101711. },
  101712. set: function (value) {
  101713. this._material.fovMultiplier = value;
  101714. },
  101715. enumerable: true,
  101716. configurable: true
  101717. });
  101718. /**
  101719. * Releases resources associated with this node.
  101720. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  101721. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  101722. */
  101723. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  101724. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  101725. this._photoTexture.dispose();
  101726. this._mesh.dispose();
  101727. this._material.dispose();
  101728. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  101729. };
  101730. return PhotoDome;
  101731. }(BABYLON.Node));
  101732. BABYLON.PhotoDome = PhotoDome;
  101733. })(BABYLON || (BABYLON = {}));
  101734. //# sourceMappingURL=babylon.photoDome.js.map
  101735. 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\nvPositionUVW=positionUpdated;\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\nvPositionUVW=positionUpdated;\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;\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\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*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;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n#ifdef BILLBOARD \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.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \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 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;\nvec3 worldPos=position+alignedCorner; \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#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\nvoid main() {\nvUV=uv;\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*size.yz*size.x;\n#ifdef BILLBOARD\n\nvec4 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\nrotatedCorner.w=0.;\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+rotatedCorner);\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\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;\n\nvec4 viewPosition=view*vec4(position+alignedCorner,1.0); \ngl_Position=projection*viewPosition;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\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 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 CONEEMITTER\nuniform float radius;\nuniform float coneAngle;\nuniform float 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\nin vec2 angle;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifdef SIZEGRADIENTS\nout vec3 outInitialSize;\n#endif\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\nin vec3 initialSize;\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() {\nif (age>=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;\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\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifdef SIZEGRADIENTS\noutInitialSize=outSize;\n#endif \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*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(CONEEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (coneAngle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutInitialSize=initialSize;\noutSize=initialSize*texture(sizeGradientSampler,vec2(age/life,0)).r;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\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}","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}","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;\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;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\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\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\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}","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}","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\nvPositionUVW=position;\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"};
  101736. 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","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","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};\n#endif\n#ifdef 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;\n#endif\n#ifdef 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 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\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\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\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","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","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}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef 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#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(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#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if 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 vec3 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 vec3 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 vec3 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#ifdef USEPHYSICALLIGHTFALLOFF\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};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,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*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*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,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*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*attenuation;\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}","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};","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","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};"};